package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.ruoyi.common.core.callback.TaskCallback;
import com.ruoyi.common.core.utils.Constant;
import com.ruoyi.common.core.utils.Global;
import com.ruoyi.common.core.utils.JwtHelper;
import com.ruoyi.common.core.utils.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.SysDict;
import com.ruoyi.system.domain.TPeopleType;
import com.ruoyi.system.domain.TestWholeData;
import com.ruoyi.system.domain.TestWholeDataRetest;
import com.ruoyi.system.domain.dto.GenerateTokenReqDTO;
import com.ruoyi.system.domain.dto.MembersDataDTO;
import com.ruoyi.system.domain.dto.MonitorDataDTO;
import com.ruoyi.system.domain.dto.SysUserLoginDTO;
import com.ruoyi.system.domain.dto.TTestPointInfoDTO;
import com.ruoyi.system.domain.dto.TestBodyfatDTO;
import com.ruoyi.system.domain.dto.TestCorporeityDTO;
import com.ruoyi.system.domain.dto.TestCorporeityResultsRetestDTO;
import com.ruoyi.system.domain.dto.TestMemberDTO;
import com.ruoyi.system.domain.dto.TestPowerDTO;
import com.ruoyi.system.domain.dto.TestPowerHeartrateDTO;
import com.ruoyi.system.domain.dto.TestTurgoscopeDTO;
import com.ruoyi.system.mapper.AnswerQuestionMapper;
import com.ruoyi.system.mapper.SysDictMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TPeopleTypeMapper;
import com.ruoyi.system.mapper.TUnionscreeningMapper;
import com.ruoyi.system.mapper.TestwholedataMapper;
import com.ruoyi.system.mapper.TestwholedataretestMapper;
import com.ruoyi.system.mapper.uploaddownload.UploadMapper;
import com.ruoyi.system.service.ReceptDataService;
import com.ruoyi.system.utils.NullStringDeserializer;
import com.ruoyi.system.utils.SignatureVerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static com.ruoyi.system.utils.UploadDataChangeUtils.appendFwcGwc;
import static com.ruoyi.system.utils.UploadDataChangeUtils.appendIfZero;
import static com.ruoyi.system.utils.UploadDataChangeUtils.appendIfZeroSafe;
import static com.ruoyi.system.utils.UploadDataChangeUtils.appendSgzgIfZero;
import static com.ruoyi.system.utils.UploadDataChangeUtils.appendWithValue;
import static com.ruoyi.system.utils.UploadDataChangeUtils.extractTestYear;
import static com.ruoyi.system.utils.UploadDataChangeUtils.getheartRate;
import static com.ruoyi.system.utils.UploadDataChangeUtils.isAgeAboveThreshold;
import static com.ruoyi.system.utils.UploadDataChangeUtils.joinDoubles;
import static com.ruoyi.system.utils.UploadDataChangeUtils.parseCoordinate;
import static com.ruoyi.system.utils.UploadDataChangeUtils.removeLastComma;
import static com.ruoyi.system.utils.UploadDataChangeUtils.toSafeFloat;
import static com.ruoyi.system.utils.UploadDataChangeUtils.truncateToMonthWithoutZeroPadFast;

@Service
public class ReceptDataServiceImpl implements ReceptDataService {

    // 存储任务ID和回调的映射关系
    private final Map<String, TaskCallback> callbackMap = new ConcurrentHashMap<>();
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private UploadMapper uploadMapper;
    @Autowired
    private SysDictMapper dictMapper;
    @Autowired
    private TPeopleTypeMapper peopleTypeMapper;
    @Autowired
    private AnswerQuestionMapper questionMapper;
    @Autowired
    private TestwholedataMapper testwholedataMapper;
    @Autowired
    private TestwholedataretestMapper testwholedataretestMapper;
    @Autowired
    private SysUserMapper sysUserInfoMapper;
    @Autowired
    private TUnionscreeningMapper unionscreeningMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SignatureVerificationService  signatureVerificationService;

/*    private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();

    public String receptData1(JSONObject data) {
        String taskId = UUID.randomUUID().toString();
// 将data类型转为String类型
        String dataStr = data.toJSONString();
        // 2. 将耗时操作通过 Kafka 异步执行
        kafkaTemplate.send("async-task-topic", "sendEmail:" + dataStr);

        // 注册回调
        callbackMap.put(taskId, (id, success, result) -> {
            // 这里处理任务完成后的回调
            System.out.println("任务[" + id + "]完成: " + (success ? "成功" : "失败"));
            System.out.println("结果: " + result);

            // 实际项目中可以：
            // 1. 更新数据库状态
            // 2. 发送通知
            // 3. 触发后续操作

            // 从映射中移除已完成的任务
            callbackMap.remove(id);
        });

        // 发送任务消息到Kafka
        kafkaTemplate.send("async-task-topic", taskId);

        return "任务已提交，ID: " + taskId;

    }
    */
    /**
     * 接收数据需要先认证
     */
    @Override
    public Object receptData(HttpServletRequest request,JSONObject data) {
//        System.out.println("--------------"+getLoginUser(request));
        System.out.println("请求开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()));
        //返回信息messageMap
        Map<String, Object> messageMap = new HashMap<>();

        String appkey = getLoginUser(request);
        if(StringUtils.isEmpty(appkey)){
            messageMap.put("code", 400);
            messageMap.put("success", false);
            messageMap.put("message", "认证已过期");
            return messageMap;
        }
        //批量插入数据库方法的参数paramMap
//        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuilder msg = new StringBuilder(); //质量筛查结果详细信息
        //批量插入数据库的条数pointsDataLimit
//        int pointsDataLimit = 1000;
        String testWholeDataTableName; //完整测试数据表名
        String testWholeDataRetestTableName; //完整测试数据复测数据表名
        String curDate; //测试数据所属的测试日期
        String version; //上传数据测试软件的版本号
        int autoNum = 0; //正常测试数据个数
        boolean flag;//是否有手工录入
        //Integer manualNum = 0; //手工录入数据个数
        int gpsNum = 0; //gps数据正确个数
        //String repeatMsg = ""; //批量上传数据时同一抽样点重复上传同一天数据返回重复提示消息
        //根据拦截器校验token时，存入ThreadLocal中的appKey,查询用户信息
        SysUserLoginDTO userMap = getAppSecret(appkey);
        //分表上传数据aloneData
//        JSONObject aloneData = (JSONObject) data.get("alone");
        //整表上传数据entiretyData
        JSONObject entiretyData = (JSONObject) data.get("entirety");
        //获取软件版本：是否属于本公司软件版本
        if (null == data.get("version") || "".equals(data.get("version"))) {
            messageMap.put("code", 400);
            messageMap.put("success", false);
            messageMap.put("message", "没有版本号");
            return messageMap;
        }
        version = data.get("version").toString();
        //数据不为空
        if (entiretyData != null) {
            //获取上传类型：批量上传or实时上传
            if (null == entiretyData.get("Upload") || "".equals(entiretyData.get("Upload"))) {
                messageMap.put("code", 400);
                messageMap.put("success", false);
                messageMap.put("message", "没有上传方式");
                return messageMap;
            }
            String uploadStatus = entiretyData.get("Upload").toString();

            //完整会员测试数据
// 在解析前注册自定义反序列化器
            ParserConfig.getGlobalInstance().putDeserializer(String.class, new NullStringDeserializer());

// 然后正常解析
            List<MembersDataDTO> membersDatas = entiretyData.getJSONArray("membersData")
                    .toJavaList(MembersDataDTO.class);
            //复测数据
            List<TestCorporeityResultsRetestDTO> testCorporeityResultsRetests = entiretyData.getJSONArray("testCorporeityResultsretest").toJavaList(TestCorporeityResultsRetestDTO.class);
// 解析完成后移除自定义反序列化器（避免影响其他解析）
            ParserConfig.getGlobalInstance().putDeserializer(Object.class, null);
//            List<MembersDataDTO> membersDatas = membersarray.toJavaList(MembersDataDTO.class);

            if (null != membersDatas && !membersDatas.isEmpty()) {
                try {
                    MembersDataDTO membersData = membersDatas.get(0);
                    //根据数据获取数据测试日期curDate,
                    curDate = membersData.getTestDate();
                    //flag上传数据是否有valueFour字段
                    flag = membersData.getValueFour()==null;
                    //根据orgId和年份查询对应的监测点testPointMap
                    Long orgId = userMap.getDeptId();
                    TTestPointInfoDTO testPointInfo = uploadMapper.selectTTestPointInfoList(curDate.substring(0, 4), orgId);
//                    System.out.println("-----"+membersData);
                    //判断用户对应的抽样点是否存在
                    if (null != testPointInfo) {
                        //查询该测试软件版本是否需要有手工录入数据
                        SysDict dictYear1 = dictMapper.selectDictByValue(version);
                        //数据字典中有该测试软件版本
                        if (null != dictYear1) {
                            String testPointGps = testPointInfo.getGps();
                            //该抽样点是否需要校验手工录入数据，isCheckRetest为0，不需要校验，isCheckRetest为1，需要校验
                            String isCheckRetest = testPointInfo.getIsCheckRetest();
                            //将监测点的GPS坐标度分秒转化成度，便于跟测试数据的GPS比较
                            //testPointGps = dms2D(testPointGps);
                            //判断该软件是否可以接受数据
                            if (0 != dictYear1.getStatus()) {
                                messageMap.put("code", 400);
                                messageMap.put("success", false);
                                messageMap.put("message", "版本受限，请使用正确的软件测试！！！");
                                return messageMap;
                            } else {
                                //校验token和时间不通过，return
                                if (!testPointInfo.getOrganizationcode().equals(membersData.getInstitutionCode()) ||
                                        !testPointInfo.getYear().equals(curDate.substring(0, 4))) {
                                    messageMap.put("code", 400);
                                    messageMap.put("success", false);
                                    messageMap.put("message", "会员所属机构与token不一致或测试数据时间与监测点时间不一致");
                                    return messageMap;
                                }
                                if(!testPointInfo.getName().equals(membersData.getInstitutionName())){
                                    messageMap.put("code", 400);
                                    messageMap.put("success", false);
                                    messageMap.put("message", "会员所属机构名称不正确，应为"+testPointInfo.getName());
                                    return messageMap;
                                }
                                //校验手工录入数据和GPS数据
                                if ("1".equals(testPointInfo.getIsCheck())) {
                                    //isCheck是1，表示需要GPS校验，校验成功后，将isCheck设置为0，当天之后的上传就不需要再进行校验
                                    //测试站点的测试幼儿的过程中，需要有多个GPS,所有需要校验多个GPS
                                    //autoNum正常测试数据个数;manualNum手工录入数据个数;gpsNum gps数据正确个数
									//2. 判断是否所以数据都接收
									//autoNum = membersData.size();
                                    if (!flag) {
                                        //没有valueFour，所有测试数据都接收
                                        autoNum = membersDatas.size();
                                    }
                                    //校验手工录入数据和GPS数据
                                    //guomintizhiTemp是一个人的国民体质测试数据
                                    for (MembersDataDTO guomintizhiTemp : membersDatas) {
                                        //校验测试数据的仪器生产厂家与版本号是否一致
                                        if (!dictYear1.getLabel().equals(guomintizhiTemp.getInstrumentManufacturer())) {
                                            //校验GPS不成功
                                            messageMap.put("code", 400);
                                            messageMap.put("success", false);
                                            messageMap.put("message", "国民体质测试数据仪器厂家名称与软件版本号不一致");
                                            return messageMap;
                                        }
                                        //flag上传数据是否有valueFour字段，有该字段且该字段不为1才是有效数据
                                        if (flag && 1!=guomintizhiTemp.getValueFour()) {
                                            //有valueFour,且valueFour不是1
                                            autoNum++;
                                        }
                                        if (!flag || 1!=guomintizhiTemp.getValueFour()) {
                                            //正常测试数据校验GPS,校验规则是选择反应时和身高的gps（这两项指标是幼儿、成人、老人都测试的），只要有符合的就通过
                                            //监测点GPS有多组，从第一组开始校验，有符合的gps，这个人的gps校验通过跳出循环
                                            String[] testPointGpsArr = testPointGps.split(";");
                                            for (String gps : testPointGpsArr) {
                                                String[] gpsCoords = gps.split(",");
                                                if (StringUtils.isNotEmpty(guomintizhiTemp.getSelectionReactionTimeGPS()) && !guomintizhiTemp.getSelectionReactionTimeGPS().equals("null")) {
                                                    if (gpsCoords.length != 2) continue;

                                                    // 2. 解析目标坐标
                                                    String[] targetCoords = guomintizhiTemp.getSelectionReactionTimeGPS().split(",");
                                                    if (targetCoords.length != 2) continue;

                                                    // 3. 转换为十进制
                                                    double gpsLat = parseCoordinate(gpsCoords[1]); // 纬度
                                                    double gpsLon = parseCoordinate(gpsCoords[0]); // 经度

                                                    double targetLat = parseCoordinate(targetCoords[0]); // 纬度
                                                    double targetLon = parseCoordinate(targetCoords[1]); // 经度

                                                    // 4. 比较（使用绝对差值更准确）
                                                    double latDiff = Math.abs(gpsLat - targetLat);
                                                    double lonDiff = Math.abs(gpsLon - targetLon);

                                                    // 5. 判断是否在误差范围内
                                                    if (latDiff <= 0.01D && lonDiff <= 0.01D) {
                                                        gpsNum++;
                                                        break;
                                                    }
                                                }
                                                if (StringUtils.isNotEmpty(guomintizhiTemp.getHeightGPS()) && !guomintizhiTemp.getHeightGPS().equals("null")) {
                                                    // 1. 解析gps坐标
                                                    if (gpsCoords.length != 2) continue;

                                                    // 2. 解析目标坐标
                                                    String[] targetCoords = guomintizhiTemp.getHeightGPS().split(",");
                                                    if (targetCoords.length != 2) continue;

                                                    // 3. 转换为十进制
                                                    double gpsLat = parseCoordinate(gpsCoords[1]); // 纬度
                                                    double gpsLon = parseCoordinate(gpsCoords[0]); // 经度

                                                    double targetLat = parseCoordinate(targetCoords[0]); // 纬度
                                                    double targetLon = parseCoordinate(targetCoords[1]); // 经度

                                                    // 4. 比较（使用绝对差值更准确）
                                                    double latDiff = Math.abs(gpsLat - targetLat);
                                                    double lonDiff = Math.abs(gpsLon - targetLon);

                                                    // 5. 判断是否在误差范围内
                                                    if (latDiff <= 0.01D && lonDiff <= 0.01D) {
                                                        gpsNum++;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    if (autoNum > 0) {
                                        //校验gps通过百分比
                                        if ((gpsNum / (double) autoNum) > 0.35) {
                                            //校验GPS正确后，设置isCheck为不需要校验
                                            testPointInfo.setIsCheck("0");
                                            //更新到数据库中
                                            uploadMapper.updateTestPointInfo("0",StringUtils.trimToEmpty(testPointInfo.getBookingDate()),StringUtils.trimToEmpty(testPointInfo.getBookingTime()),testPointInfo.getId());
                                        } else {
                                            //校验GPS不成功
                                            messageMap.put("code", 400);
                                            messageMap.put("success", false);
                                            messageMap.put("message", "国民体质测试数据GPS与抽样点GPS不一致");
                                            return messageMap;
                                        }
                                    } else {
                                        //无有效数据
                                        messageMap.put("code", 400);
                                        messageMap.put("success", false);
                                        messageMap.put("message", "无有效数据");
                                        return messageMap;
                                    }
                                }

                                //查询当前数据年份对应的数据表标识符
                                SysDict dictYear = dictMapper.selectDictByLabel(curDate.substring(0, 4));
                                //数据字典中没有当前年份数据表标识符
                                if (dictYear == null) {
                                    //计算出当前年份数据表标识符curTag
                                    String curTag = Global.getCurTag(curDate.substring(0, 4));
                                    if (curTag.isEmpty()) {
                                        messageMap.put("code", 400);
                                        messageMap.put("success", false);
                                        messageMap.put("message", "上传数据不能早于2020年");
                                        return messageMap;
                                    }
                                    //插入数据字典表中
                                    dictYear = new SysDict();
                                    dictYear.setValue(curTag);
                                    dictYear.setLabel(curDate.substring(0, 4));
                                    dictYear.setType("year");
                                    dictYear.setDescription(curDate.substring(0, 4) + "年数据表标识符是" + curTag);
                                    dictYear.setSort(0);
                                    dictYear.setStatus(0);
                                    dictMapper.insertDict(dictYear);

                                }
                                //根据年份生成对应的表名
                                testWholeDataTableName = Global.DATATABLEPRE + "_" + dictYear.getValue() + Global.TESTWHOLEDATANAME;
                                testWholeDataRetestTableName = Global.DATATABLEPRE + "_" + dictYear.getValue() + Global.RETESTWHOLEDATANAME;
                                //判断该年份的数据表是否存在，不存在创建，存在不创建
                                uploadMapper.createDataTable(testWholeDataTableName, Global.DATATABLEPRE + "_" + Global.DATATABLESTARTTAG + Global.TESTWHOLEDATANAME);
                                uploadMapper.createDataTable(testWholeDataRetestTableName, Global.DATATABLEPRE + "_" + Global.DATATABLESTARTTAG + Global.RETESTWHOLEDATANAME);

                                if ("batch1".equals(uploadStatus)) {

                                    String dataStr = data.toJSONString();
//                                    System.out.println("---^-^---正在批量发送测试数据，数据为：" + dataStr);
                                    // 2. 将耗时操作通过 Kafka 异步执行
                                    kafkaTemplate.send("async-task-topic", "sendEmail|@|" + dataStr + "|@|" + appkey);
                                    //  批量上传
                                    messageMap.put("code", 200);
                                    messageMap.put("success", true);
                                    messageMap.put("message", "已传到后台处理！");
                                    return messageMap;
                                } else if ("RealTime1".equals(uploadStatus)) {
                                    //解析数据,必须上传一个人的数据，判断size=1
                                    if (membersDatas.size() == 1) {
                                        System.out.println("正在实时接收测试数据，数据为：" + membersDatas.size());
                                        //该抽样点是否需要校验手工录入数据，isCheckRetest为0，不需要校验，isCheckRetest为1，需要校验
                                        //手工录入标识是1，手工录入数据不接受
                                        if (!"1".equals(isCheckRetest) || !flag || 1!=membersData.getValueFour()) {
                                            // 数据转换  引用
                                            TestWholeData testWholeData = getTestWholeData(membersData, msg);
                                            //单条插入数据库
                                            try {
                                                //先质控筛查，然后插入数据库
                                                System.out.println("-------------------"+testWholeDataTableName);
                                                //查询该idcard,testtime的完整测试数据是否已经存在，存在更新，不存在插入
                                                TestWholeData testWholeDataTmp = testwholedataMapper.getByTableName(testWholeData, testWholeDataTableName);
                                                if (null == testWholeDataTmp) {
                                                    testwholedataMapper.insertByTableName(testWholeData, testWholeDataTableName);
                                                } else {
                                                    testWholeData.setId(testWholeDataTmp.getId());
                                                    testwholedataMapper.updateByTableName(testWholeData, testWholeDataTableName);
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                messageMap.put("code", 400);
                                                messageMap.put("success", false);
                                                messageMap.put("message", "数据上传失败，插入数据库发生异常，请联系平台管理员");
                                            }

                                            try {
                                                //查看受试者是否填写问卷
                                                List<Map<String, Object>> questionList = questionMapper.selectByIdcardYear(testWholeData.getIdcard(), testWholeData.getTesttime().substring(0, 4));
                                                if (null != questionList && !questionList.isEmpty()) {
                                                    msg.append("问卷已完成。");
                                                } else {
                                                    msg.append("问卷未完成。");
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                messageMap.put("code", 200);
                                                messageMap.put("success", true);
                                                messageMap.put("message", msg + "问卷查看异常。");
                                            }
                                        }
                                    } else {
                                        messageMap.put("code", 400);
                                        messageMap.put("success", false);
                                        messageMap.put("message", "不支持多人上传");
                                    }
                                    System.out.println("整表实时接收处理完成时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()));

                                    //解析复测数据,同一个会员同一天只保留一次复测数据，如果存在会更新，不存在插入
                                    if (null != testCorporeityResultsRetests && !testCorporeityResultsRetests.isEmpty()) {
                                        TestCorporeityResultsRetestDTO testCorporeityResultsRetest = testCorporeityResultsRetests.get(0);
                                        System.out.println("正在实时接收复测数据：数量为：" + testCorporeityResultsRetests.size());
                                        // 数据转换  引用
                                        TestWholeDataRetest testWholeDataRetest = getTestWholeDataRetest(testCorporeityResultsRetest);
                                        //单条插入数据库
                                        try {
                                            //查询该idcard,testtime的完整测试数据是否已经存在，存在更新，不存在插入,这里复测数据还是一个人，一天只能有一条记录，如果有多次复测记录会覆盖
                                            TestWholeDataRetest testWholeDataRetestTmp = testwholedataretestMapper.getByTableName(testWholeDataRetest, testWholeDataRetestTableName);
                                            if (null == testWholeDataRetestTmp) {
                                                testwholedataretestMapper.insertByTableName(testWholeDataRetest, testWholeDataRetestTableName);
                                            } else {
                                                testWholeDataRetest.setId(testWholeDataRetestTmp.getId());
                                                testwholedataretestMapper.updateByTableName(testWholeDataRetest, testWholeDataRetestTableName);
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            messageMap.put("code", 400);
                                            messageMap.put("success", false);
                                            messageMap.put("message", "数据上传失败，插入数据库发生异常，请联系平台管理员");
                                        }

                                    }
                                } else {
                                    messageMap.put("code", 400);
                                    messageMap.put("success", false);
                                    messageMap.put("message", "没有上传方式");
                                    return messageMap;
                                }
                                System.out.println("整表实时上传处理完成时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss sss").format(new Date()));
                                messageMap.put("code", 200);
                                messageMap.put("success", true);
                                messageMap.put("message", msg.toString());

                                //处理分表数据

                            }
                        } else {
                            messageMap.put("code", 400);
                            messageMap.put("success", false);
                            messageMap.put("message", "版本受限，请使用正确的软件测试");
                            return messageMap;
                        }

                    } else {
                        messageMap.put("code", 400);
                        messageMap.put("success", false);
                        messageMap.put("message", "用户对应的抽样点不存在");
                        return messageMap;
                    }
                } catch (Exception e) {
                    messageMap.put("code", 400);
                    messageMap.put("success", false);
                    messageMap.put("message", "数据上传失败，插入数据库发生异常，请联系平台管理员");
                    return messageMap;
                }
            } else {
                messageMap.put("code", 400);
                messageMap.put("success", false);
                messageMap.put("message", "没有测试数据");
                return messageMap;
            }
        } else {
            messageMap.put("code", 400);
            messageMap.put("success", false);
            messageMap.put("message", "没有测试数据");
            return messageMap;
        }
        return messageMap;
    }

    /**
     * 接收数据，带有token，直接上传
     */
    @Override
    public Object receptDataNoAuth(HttpServletRequest request,JSONObject data) {
//        System.out.println("---------------"+SecurityUtils.getUsername()+"---"+SecurityUtils.getUserKey());
//        System.out.println("--------------"+getLoginUser(request));
        System.out.println("请求开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date()));
        //返回信息messageMap
        Map<String, Object> messageMap = new HashMap<>();

        //批量插入数据库方法的参数paramMap
//        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuilder msg = new StringBuilder(); //质量筛查结果详细信息
        //批量插入数据库的条数pointsDataLimit
//        int pointsDataLimit = 1000;
        String testWholeDataTableName; //完整测试数据表名
        String testWholeDataRetestTableName; //完整测试数据复测数据表名
        String curDate=""; //测试数据所属的测试日期
        int autoNum = 0; //正常测试数据个数
//        boolean flag;//是否有手工录入
        //Integer manualNum = 0; //手工录入数据个数
        int gpsNum = 0; //gps数据正确个数
//        int pointsDataLimit = 1000;

        String version = ""; //上传数据测试软件的版本号
        Integer manualNum = 0; //手工录入数据个数
        String repeatMsg = ""; //批量上传数据重复上传返回消息
        //String repeatMsg = ""; //批量上传数据时同一抽样点重复上传同一天数据返回重复提示消息
        String requestUri = request.getRequestURI();
        String token = requestUri.substring(requestUri.lastIndexOf("/")+1);
//        System.out.println("-----token："+token);
        TTestPointInfoDTO testPointInfo = uploadMapper.selectTTestPointInfoByToken(token);
//判断token对应的抽样点是否存在
        if(null != testPointInfo){
            //获取软件版本：是否属于本公司软件版本
            version = data.get("version").toString();
            //查询该测试软件版本是否需要有手工录入数据
            SysDict dictYear1 = dictMapper.selectDictByValue(version);
            //数据字典中有该测试软件版本
            if(null != dictYear1){
                String testPointGps = testPointInfo.getGps();
                //该抽样点是否需要校验手工录入数据，isCheckRetest为0，不需要校验，isCheckRetest为1，需要校验
                String isCheckRetest = testPointInfo.getIsCheckRetest();
                //分表上传数据aloneData
                JSONObject aloneData = (JSONObject) data.get("alone");
                JSONObject entiretyData = (JSONObject) data.get("entirety");
                //testPointGps = dms2D(testPointGps);
                //判断该软件是否可以接受数据
                if (0 != dictYear1.getStatus()) {
                    messageMap.put("code", 400);
                    messageMap.put("success", false);
                    messageMap.put("message", "版本受限，请使用正确的软件测试！！！");
                    return messageMap;
                //整表上传数据entiretyData
                } else {
                    //分表上传数据不为空
                    if(aloneData != null){
                        //获取上传类型：批量上传or实时上传
                        String uploadStatus = aloneData.get("Upload").toString();
                        ParserConfig.getGlobalInstance().putDeserializer(String.class, new NullStringDeserializer());

//                        if (aloneData == null) return;
                        //会员信息members
                        List<TestMemberDTO> members = aloneData.getJSONArray("members").toJavaList(TestMemberDTO.class);
                        //国民体质数据testCorporeityResults
                        List<Map<String, Object>> testCorporeityResults = (List<Map<String, Object>>) aloneData.get("testCorporeityResults");
                        //国民体质复测数据testCorporeityResultsretest
                        List<Map<String, Object>> testCorporeityResultsretest = (List<Map<String, Object>>) aloneData.get("testCorporeityResultsretest");
                        //血压计数据testTurgoscopeResults
                        List<Map<String, Object>> testTurgoscopeResults = (List<Map<String, Object>>) aloneData.get("testTurgoscopeResult");
                        //体脂率数据testBodyFatResults
                        List<Map<String, Object>> testBodyFatResults = (List<Map<String, Object>>) aloneData.get("testBodyFatResult");
                        //功率车数据testPowerResults
                        List<Map<String, Object>> testPowerResults = (List<Map<String, Object>>) aloneData.get("testPowerResult");
                        //功率车心率数据testPowerHeartrateResults
                        List<Map<String, Object>> testPowerHeartrateResults = (List<Map<String, Object>>) aloneData.get("testPowerHeartrateResult");
                        //获取测试数据所属的测试年份
                        // 3. 获取测试年份
                        if (testCorporeityResults != null && !testCorporeityResults.isEmpty()) {
                            curDate = extractTestYear(testCorporeityResults, "TestCorporeityResults");
                        }
                        if (StringUtils.isEmpty(curDate) && testTurgoscopeResults != null && !testTurgoscopeResults.isEmpty()) {
                            curDate = extractTestYear(testTurgoscopeResults, "TestTurgoscopeResults");
                        }
                        if (StringUtils.isEmpty(curDate) && testBodyFatResults != null && !testBodyFatResults.isEmpty()) {
                            curDate = extractTestYear(testBodyFatResults, "TestBodyFatResults");
                        }
                        if (StringUtils.isEmpty(curDate) && testPowerResults != null && !testPowerResults.isEmpty()) {
                            curDate = extractTestYear(testPowerResults, "TestPowerResults");
                        }
                        ParserConfig.getGlobalInstance().putDeserializer(Object.class, null);

                        //curDate = members.get(0).get("createtime").toString();
                        //校验数据的机构代码和token一致，测试数据时间和抽样点一致，不通过，return
                        //校验token和时间不通过，return
                        if(!testPointInfo.getOrganizationcode().equals(members.get(0).getMechanismcode())){
                            messageMap.put("success", false);
                            messageMap.put("code", 400);
                            messageMap.put("message", "测试数据机构代码不正确");
                            return messageMap;
                        }
                        if(!testPointInfo.getName().equals(testCorporeityResults.get(0).get("mechanismName"))){
                            messageMap.put("code", 400);
                            messageMap.put("success", false);
                            messageMap.put("message", "会员所属机构名称不正确，应为"+testPointInfo.getName());
                            return messageMap;
                        }
                        if(!testPointInfo.getYear().equals(curDate.substring(0, 4))){
                            messageMap.put("success", false);
                            messageMap.put("code", 400);
                            messageMap.put("message", "测试数据时间不正确");
                            return messageMap;
                        }
                        //校验手工录入数据和GPS数据
                        if("1".equals(testPointInfo.getIsCheck())){
                            //isCheck是1，表示需要GPS校验，校验成功后，将isCheck设置为0，当天之后的上传就不需要再进行校验
                            //测试站点的测试幼儿的过程中，需要有多个GPS,所有需要校验多个GPS
                            //autoNum正常测试数据个数;manualNum手工录入数据个数;gpsNum gps数据正确个数
							/*//2. 所有测试数据都接受
							autoNum = testCorporeityResults.size();*/
                            //校验手工录入数据和GPS数据
                            //guomintizhiTemp是一个人的国民体质测试数据
                            // 预先解析测试点GPS坐标（避免在循环中重复拆分）
                            List<double[]> testPoints = new ArrayList<>();
                            if (testPointGps != null && !testPointGps.isEmpty()) {
                                String[] testPointGpsArr = testPointGps.split(";");
                                for (String gps : testPointGpsArr) {
                                    String[] parts = gps.split(",");
                                    if (parts.length == 2) {
                                        try {
                                            System.out.println("-------------------------");
                                            // 注意：测试点GPS格式是"经度,纬度"
                                            double lng = Double.parseDouble(parts[0]); // 经度
                                            double lat = Double.parseDouble(parts[1]); // 纬度
                                            testPoints.add(new double[]{lat, lng});
                                        } catch (NumberFormatException ignore) {
                                            // 忽略格式错误的坐标点
                                        }
                                    }
                                }
                            }
                            for (Map<String, Object> guomintizhiTemp : testCorporeityResults) {
                                // 保持原始层级结构
                                List<Map<String, Object>> results = (List<Map<String, Object>>) guomintizhiTemp.get("TestCorporeityResults");
                                if (results == null || results.isEmpty()) continue;

                                Map<String, Object> map = results.get(0);
                                Object valueFour = map.get("valueFour");

                                // 处理手工录入数据
                                if (valueFour != null && "1".equals(valueFour.toString())) {
                                    manualNum++;
                                    continue; // 手工数据跳过GPS检查
                                }

                                autoNum++;

                                // 正常测试数据校验GPS
                                Object gpsObj = map.get("gps");
                                if (gpsObj == null) continue;

                                String gpsStr = gpsObj.toString().trim();
                                if (gpsStr.isEmpty() || "null".equalsIgnoreCase(gpsStr)) continue;

                                // 解析数据GPS坐标
                                String[] dataGpsParts = gpsStr.split(",");
                                if (dataGpsParts.length != 2) continue;

                                try {
                                    // 注意：数据GPS格式是"纬度,经度"
                                    double dataLat = Double.parseDouble(dataGpsParts[0]); // 纬度
                                    double dataLng = Double.parseDouble(dataGpsParts[1]); // 经度

                                    // 与所有测试点比较
                                    for (double[] point : testPoints) {
                                        double pointLat = point[0]; // 测试点纬度
                                        double pointLng = point[1]; // 测试点经度

                                        // 使用绝对差值比较（更清晰）
                                        double latDiff = Math.abs(pointLat - dataLat);
                                        double lngDiff = Math.abs(pointLng - dataLng);

                                        // 0.01度 ≈ 1.1公里
                                        if (latDiff <= 0.01D && lngDiff <= 0.01D) {
                                            gpsNum++;
                                            break; // 匹配成功即跳出
                                        }
                                    }
                                } catch (NumberFormatException ignore) {
                                    // 忽略格式错误的坐标
                                }
                            }
                            //有正常测试数据才GPS校验，手工录入数据不需要GPS校验
                            if(autoNum > 0){
                                //校验gps通过百分比
                                if((gpsNum / (double) autoNum) > 0.35){
                                    //校验GPS正确后，设置isCheck为不需要校验
                                    testPointInfo.setIsCheck("0");
                                    //更新到数据库中
                                    uploadMapper.updateTestPointInfo("0",StringUtils.trimToEmpty(testPointInfo.getBookingDate()),StringUtils.trimToEmpty(testPointInfo.getBookingTime()),testPointInfo.getId());
                                }else {
                                    //校验GPS不成功
                                    messageMap.put("success", false);
                                    messageMap.put("code", 400);
                                    messageMap.put("message", "国民体质测试数据GPS与抽样点GPS不一致");
                                    return messageMap;
                                }
                            }
                        }
                        //查询当前数据年份对应的数据表标识符
                        SysDict dictYear = dictMapper.selectDictByLabel(curDate.substring(0, 4));
                        //数据字典中没有当前年份数据表标识符
                        if (dictYear == null) {
                            //计算出当前年份数据表标识符curTag
                            String curTag = Global.getCurTag(curDate.substring(0, 4));
                            if (curTag.isEmpty()) {
                                messageMap.put("code", 400);
                                messageMap.put("success", false);
                                messageMap.put("message", "上传数据不能早于2020年");
                                return messageMap;
                            }
                            //插入数据字典表中
                            dictYear = new SysDict();
                            dictYear.setValue(curTag);
                            dictYear.setLabel(curDate.substring(0, 4));
                            dictYear.setType("year");
                            dictYear.setDescription(curDate.substring(0, 4) + "年数据表标识符是" + curTag);
                            dictYear.setSort(0);
                            dictYear.setStatus(0);
                            dictMapper.insertDict(dictYear);

                        }
                        //根据年份生成对应的表名
                        testWholeDataTableName = Global.DATATABLEPRE + "_" + dictYear.getValue() + Global.TESTWHOLEDATANAME;
                        testWholeDataRetestTableName = Global.DATATABLEPRE + "_" + dictYear.getValue() + Global.RETESTWHOLEDATANAME;
                        //判断该年份的数据表是否存在，不存在创建，存在不创建
                        uploadMapper.createDataTable(testWholeDataTableName, Global.DATATABLEPRE + "_" + Global.DATATABLESTARTTAG + Global.TESTWHOLEDATANAME);
                        uploadMapper.createDataTable(testWholeDataRetestTableName, Global.DATATABLEPRE + "_" + Global.DATATABLESTARTTAG + Global.RETESTWHOLEDATANAME);

                        //批量上传
                        if("batch".equals(uploadStatus)){

                            String dataStr = data.toJSONString();
//                                    System.out.println("---^-^---正在批量发送测试数据，数据为：" + dataStr);
                            // 2. 将耗时操作通过 Kafka 异步执行
                            kafkaTemplate.send("async-Token-topic", "sendEmail|@|" + dataStr + "|@|" + token);
                            //  批量上传
                            messageMap.put("code", 200);
                            messageMap.put("success", true);
                            messageMap.put("message", "已传到后台处理！");
                            return messageMap;
                        }
                        //实时上传
                        if("RealTime".equals(uploadStatus)){
                            //实时接收会员信息
                            TestMemberDTO uniqueMember = members.get(0);
                            // 处理国民体质数据（原始）
                            // 处理国民体质数据（获取整个有效列表）
                            List<TestCorporeityDTO> guomintizhiDataList = processTestDataList(
                                    isCheckRetest,
                                    testCorporeityResults,
                                    "TestCorporeityResults",
                                    TestCorporeityDTO.class
                            );

                            // 处理国民体质复测数据（获取整个有效列表）
                            List<TestCorporeityDTO> guomintizhiRetestDataList = processTestDataList(
                                    isCheckRetest,
                                    testCorporeityResultsretest,
                                    "TestCorporeityResultCopies",
                                    TestCorporeityDTO.class
                            );

                            // 处理血压数据
                            TestTurgoscopeDTO turgoscopeData = processSingleTestData(
                                    isCheckRetest,
                                    testTurgoscopeResults,
                                    "TestTurgoscopeResults",
                                    TestTurgoscopeDTO.class
                            );

                            // 处理体脂数据
                            TestBodyfatDTO bodyfatData = processSingleTestData(
                                    isCheckRetest,
                                    testBodyFatResults,
                                    "TestBodyFatResults",
                                    TestBodyfatDTO.class
                            );

                            // 处理功率数据
                            TestPowerDTO powerData = processSingleTestData(
                                    isCheckRetest,
                                    testPowerResults,
                                    "TestPowerResults",
                                    TestPowerDTO.class
                            );

                            // 处理心率数据
                            TestPowerHeartrateDTO heartrateData = processSingleTestData(
                                    isCheckRetest,
                                    testPowerHeartrateResults,
                                    "TestPowerHeartrates",
                                    TestPowerHeartrateDTO.class
                            );

                            // 3. 为每个数据创建独立处理上下文
                            TestWholeData testWholeData = new TestWholeData();

                            // 4. 打印当前处理的数据ID
//                                            System.out.println("处理数据: " + combinedData.getTestTime());

                            // 5. 设置公共字段
                            testWholeData.setStatus(1);
                            testWholeData.setIdcard(uniqueMember.getIdcard());
                            setmembers(testWholeData, uniqueMember);

                            // 6. 安全处理测试年龄
                            Double testAge = getFirstValidTestAge(
                                    guomintizhiDataList,
                                    turgoscopeData,
                                    bodyfatData,
                                    powerData,
                                    heartrateData
                            );
                            testWholeData.setTestage(toSafeFloat(testAge));

                            testWholeData.setTesttime(guomintizhiDataList.get(0).getTestTime());
                            testWholeData.setTestmonth(truncateToMonthWithoutZeroPadFast(guomintizhiDataList.get(0).getTestTime()));
                            testWholeData.setType(1);

                            // 7. 使用局部变量而非共享数组
                            String gps = "0.000,0.000";

                            // 8. 处理体测数据 - 添加空检查
                            if (!guomintizhiDataList.isEmpty()) {
                                gps = processCorporeitys(testWholeData, guomintizhiDataList); // 修改为返回GPS的方法
                            }
                            testWholeData.setGps(gps);

                            // 9. 处理功率车数据 - 添加空检查
                            if (powerData != null) {
                                testWholeData.setMetval(toSafeFloat(powerData.getMetvalue()));
                                testWholeData.setRelativeval(toSafeFloat(powerData.getRelativevalue()));
                                testWholeData.setAbsoluteval(toSafeFloat(powerData.getAbsolutevalue()));

                                // 10. 安全处理心率
                                String heartRate = getheartRate(powerData.getGlcHeartRate(), heartrateData);
                                testWholeData.setGlcHeartRate(heartRate);

                                testWholeData.setGlcspecifictime(StringUtils.trimToEmpty(powerData.getSpecifictime()));
                                testWholeData.setGlctablegps(StringUtils.trimToEmpty(powerData.getGps()));
                            }

                            // 11. 处理血压计数据 - 重构逻辑
                            if (turgoscopeData != null) {
                                // 添加空指针保护
                                Integer heartrate = turgoscopeData.getHeartrate();
                                if (heartrate == null) {
                                    // 安全处理年龄
//                                                    Float turgoscopeAge = toSafeFloat(turgoscope.getTestage());
                                    if (turgoscopeData.getTestage() != null && isAgeAboveThreshold(turgoscopeData.getTestage(), 20.0f)) {
                                        testWholeData.setStatus(0);
                                    }
                                } else {
                                    testWholeData.setHeartrate(heartrate);
                                    testWholeData.setDiastolicpressure(turgoscopeData.getDiastolicpressure());
                                    testWholeData.setSystolicpressure(turgoscopeData.getSystolicpressure());
                                    testWholeData.setXyjspecifictime(StringUtils.trimToEmpty(turgoscopeData.getSpecifictime()));
                                    testWholeData.setXyjgps(StringUtils.trimToEmpty(turgoscopeData.getGps()));
                                }
                            }

                            // 12. 处理体脂数据
                            if (bodyfatData != null) {
                                setbodyfat(testWholeData, bodyfatData);
                            }
                            if (1 == testWholeData.getStatus()) {
                                try {
                                    //是否筛查通过，一个人的各项指标质量筛查结果monitorData
                                    List<MonitorDataDTO> monitorData = unionscreeningMapper.getMonitorResult(testWholeData);
                                    //查出所有人群类型（幼儿，成年人，老年人），按照人群类型进行逻辑筛查
                                    List<TPeopleType> peopleTypeList = peopleTypeMapper.getAllList();
                                    for (TPeopleType tPeopleType : peopleTypeList) {
                                        if (testWholeData.getTestage() >= tPeopleType.getPeopleagemin() && testWholeData.getTestage() < tPeopleType.getPeopleagemax()) {
                                            //返回这个人各指标详细的逻辑筛查不通过信息，
                                            String message = "";
                                            StringBuilder messageBuilder = new StringBuilder();
                                            if (monitorData != null && !monitorData.isEmpty()) {
                                                // 确保第一个元素存在
                                                MonitorDataDTO peopledata = monitorData.get(0);
                                                if (tPeopleType.getId()==1) {

                                                    // 使用辅助方法判断各字段
                                                    appendIfZero(messageBuilder, peopledata.getShengao(), "身高");
                                                    appendIfZero(messageBuilder, peopledata.getZuogao(), "坐高");
                                                    appendIfZero(messageBuilder, peopledata.getTizhong(), "体重");
                                                    appendIfZero(messageBuilder, peopledata.getXiongwei(), "胸围");
                                                    appendIfZero(messageBuilder, peopledata.getTzl(), "体脂率");
                                                    appendIfZero(messageBuilder, peopledata.getAjxl(), "安静心率");
                                                    appendIfZero(messageBuilder, peopledata.getWoli(), "握力");
                                                    appendIfZero(messageBuilder, peopledata.getLdty(), "立定跳远");
                                                    appendIfZero(messageBuilder, peopledata.getZwtqq(), "坐位体前屈");
                                                    appendIfZero(messageBuilder, peopledata.getSjlxt(), "双脚连续跳");
                                                    appendIfZero(messageBuilder, peopledata.getZphm(), "走平衡木");
                                                    appendIfZero(messageBuilder, peopledata.getSwmrzap(), "15米绕障碍跑");
                                                    appendSgzgIfZero(messageBuilder, peopledata.getSgzg(), peopledata.getSgzgval());
                                                    appendIfZero(messageBuilder, peopledata.getShengaotizhong(), "身高与体重");
                                                    appendIfZero(messageBuilder, peopledata.getShengaozuogao(), "身高与坐高");
                                                } else if (tPeopleType.getId()==2) {
                                                    // 添加所有字段检查
                                                    appendIfZero(messageBuilder, peopledata.getShengao(), "身高");
                                                    appendIfZero(messageBuilder, peopledata.getTizhong(), "体重");
                                                    appendIfZero(messageBuilder, peopledata.getYaowei(), "腰围");
                                                    appendIfZero(messageBuilder, peopledata.getTunwei(), "臀围");
                                                    appendIfZero(messageBuilder, peopledata.getTzl(), "体脂率");
                                                    appendIfZero(messageBuilder, peopledata.getFhl(), "肺活量");
                                                    appendIfZero(messageBuilder, peopledata.getGlc(), "功率车");
                                                    appendIfZero(messageBuilder, peopledata.getWoli(), "握力");
                                                    appendIfZero(messageBuilder, peopledata.getZongtiao(), "纵跳");
                                                    appendFwcGwc(messageBuilder, peopledata.getFwc(), peopledata.getGwc());
                                                    appendIfZero(messageBuilder, peopledata.getYfzywqz(), "1分钟仰卧起坐");
                                                    appendIfZero(messageBuilder, peopledata.getZwtqq(), "坐位体前屈");
                                                    appendIfZero(messageBuilder, peopledata.getBydjzl(), "闭眼单脚站立");
                                                    appendIfZero(messageBuilder, peopledata.getXzfys(), "选择反应时");
                                                    appendIfZero(messageBuilder, peopledata.getBeili(), "背力");
                                                    appendIfZero(messageBuilder, peopledata.getHeartrate(), "安静脉搏");
                                                    appendIfZero(messageBuilder, peopledata.getSystolicpressure(), "收缩压");
                                                    appendIfZero(messageBuilder, peopledata.getDiastolicpressure(), "舒张压");

                                                    // 特殊字段
                                                    appendWithValue(messageBuilder, peopledata.getYaoweitunwei(), peopledata.getYaoweitunweival(), "腰臀比");
                                                    appendWithValue(messageBuilder, peopledata.getMaiyacha(), peopledata.getMaiyachaval(), "脉压差");

                                                    // 组合字段
                                                    appendIfZero(messageBuilder, peopledata.getShengaotizhong(), "身高与体重");
                                                    appendIfZero(messageBuilder, peopledata.getShengaofhl(), "身高与肺活量");
                                                    appendIfZero(messageBuilder, peopledata.getShengaowoli(), "身高与握力");
                                                    appendIfZero(messageBuilder, peopledata.getShengaobeili(), "身高与背力");
                                                    appendIfZero(messageBuilder, peopledata.getTizhongfhl(), "体重与肺活量");
                                                    appendIfZero(messageBuilder, peopledata.getTizhongwoli(), "体重与握力");
                                                    appendIfZero(messageBuilder, peopledata.getTizhongbeili(), "体重与背力");
                                                    appendIfZero(messageBuilder, peopledata.getYaoweishengaotizhong(), "腰围/身高与体重");
                                                    appendIfZero(messageBuilder, peopledata.getTunweishengaotizhong(), "臀围/身高与体重");

                                                    // 移除末尾顿号
//                                                                removeLastComma(builder);
                                                } else if (tPeopleType.getId()==3) {
                                                    // 添加所有字段检查
                                                    appendIfZero(messageBuilder, peopledata.getShengao(), "身高");
                                                    appendIfZero(messageBuilder, peopledata.getTizhong(), "体重");
                                                    appendIfZeroSafe(messageBuilder, peopledata.getYaowei(), "腰围");
                                                    appendIfZeroSafe(messageBuilder, peopledata.getTunwei(), "臀围");
                                                    appendIfZero(messageBuilder, peopledata.getTzl(), "体脂率");
                                                    appendIfZero(messageBuilder, peopledata.getFhl(), "肺活量");
                                                    appendIfZero(messageBuilder, peopledata.getLfzydgtt(), "2分钟原地高抬腿");
                                                    appendIfZero(messageBuilder, peopledata.getWoli(), "握力");
                                                    appendIfZero(messageBuilder, peopledata.getZwtqq(), "坐位体前屈");
                                                    appendIfZero(messageBuilder, peopledata.getBydjzl(), "闭眼单脚站立");
                                                    appendIfZero(messageBuilder, peopledata.getXzfys(), "选择反应时");
                                                    appendIfZero(messageBuilder, peopledata.getSsmzz(), "30秒坐站");
                                                    appendIfZero(messageBuilder, peopledata.getHeartrate(), "安静脉搏");
                                                    appendIfZero(messageBuilder, peopledata.getSystolicpressure(), "收缩压");
                                                    appendIfZero(messageBuilder, peopledata.getDiastolicpressure(), "舒张压");

                                                    // 特殊字段
                                                    appendWithValue(messageBuilder, peopledata.getYaoweitunwei(), peopledata.getYaoweitunweival(), "腰臀比");
                                                    appendWithValue(messageBuilder, peopledata.getMaiyacha(), peopledata.getMaiyachaval(), "脉压差");

                                                    // 组合字段
                                                    appendIfZero(messageBuilder, peopledata.getShengaotizhong(), "身高与体重");
                                                    appendIfZero(messageBuilder, peopledata.getShengaofhl(), "身高与肺活量");
                                                    appendIfZero(messageBuilder, peopledata.getShengaowoli(), "身高与握力");
                                                    appendIfZero(messageBuilder, peopledata.getTizhongfhl(), "体重与肺活量");
                                                    appendIfZero(messageBuilder, peopledata.getTizhongwoli(), "体重与握力");
                                                    appendIfZeroSafe(messageBuilder, peopledata.getYaoweishengaotizhong(), "腰围/身高与体重");
                                                    appendIfZeroSafe(messageBuilder, peopledata.getTunweishengaotizhong(), "臀围/身高与体重");
                                                }
                                                removeLastComma(messageBuilder);
                                                message = messageBuilder.toString();
                                            }

                                            if (!message.isEmpty()) {
                                                //message不是空，说明有筛查不合格的指标，将这个人筛查不通过放入testWholeData的ispassscreening
                                                testWholeData.setIspassscreening(0);
                                                //筛查不通过指标名称，放入testWholeData的itemsispass
                                                testWholeData.setItemsispass(message);
                                                //返回前端筛查不通过指标名称
                                                msg.append(testWholeData.getRealname()).append(message).append("筛查不通过。");
                                            } else {
                                                //message是空，说明没有筛查不合格的指标，将这个人筛查通过放入testWholeData的ispassscreening
                                                testWholeData.setIspassscreening(1);
                                            }
                                        }
                                    }
                                }catch (Exception e){
                                    messageMap.put("code", 400);
                                    messageMap.put("success", false);
                                    messageMap.put("message", "质量筛查失败！");
                                }
                            }
                            //单条插入数据库
                            try {
                                //先质控筛查，然后插入数据库
//                                System.out.println("-------------------"+testWholeDataTableName);
                                //查询该idcard,testtime的完整测试数据是否已经存在，存在更新，不存在插入
                                TestWholeData testWholeDataTmp = testwholedataMapper.getByTableName(testWholeData, testWholeDataTableName);
                                if (null == testWholeDataTmp) {
                                    int i = testwholedataMapper.insertByTableName(testWholeData, testWholeDataTableName);
                                } else {
                                    testWholeData.setId(testWholeDataTmp.getId());
                                    int i = testwholedataMapper.updateByTableName(testWholeData, testWholeDataTableName);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                messageMap.put("code", 400);
                                messageMap.put("success", false);
                                messageMap.put("message", e);
                            }

                            if (!guomintizhiRetestDataList.isEmpty()) {


                                // 创建一个项目ID到DTO的映
                                Map<Integer, TestCorporeityDTO> itemMap = new HashMap<>();

                                // 遍历所有数据，按项目ID分组
                                for (TestCorporeityDTO dto : guomintizhiRetestDataList) {
                                    // 获取项目ID（确保不为null）
                                    Integer itemCode = dto.getItemCode() != null ? dto.getItemCode() : 0;

                                    // 直接放入映射（不需要分组，因为所有数据都属于同一个测试）
                                    itemMap.put(itemCode, dto);
                                }
                                TestCorporeityDTO firstDto = guomintizhiRetestDataList.get(0);
                                // 创建完整复测测试数据
                                TestWholeDataRetest testWholeDataRetest = new TestWholeDataRetest();
                                testWholeDataRetest.setSex(uniqueMember.getSex());
                                testWholeDataRetest.setIdcard(uniqueMember.getIdcard());
                                testWholeDataRetest.setTowncountry(StringUtils.trimToEmpty(uniqueMember.getTownAndCountry()));
                                testWholeDataRetest.setMechanismcode(StringUtils.trimToEmpty(uniqueMember.getMechanismcode()));

                                // 获取第一个DTO作为基础数据
                                testWholeDataRetest.setTestage(toSafeFloat(firstDto.getTestAge()));
                                testWholeDataRetest.setTesttime(firstDto.getTestTime());
                                testWholeDataRetest.setTestmonth(truncateToMonthWithoutZeroPadFast(firstDto.getTestTime()));
                                testWholeDataRetest.setGps(StringUtils.trimToEmpty(firstDto.getGps()));

                                // 使用重载的applyItemData方法设置各项数据
                                applyItemData(itemMap.get(1),
                                        testWholeDataRetest::setShengaoval,
                                        testWholeDataRetest::setShengaoscore,
                                        testWholeDataRetest::setShengaograde,
                                        testWholeDataRetest::setShengaotime);

                                applyItemData(itemMap.get(3),
                                        testWholeDataRetest::setZuogaoval,
                                        testWholeDataRetest::setZuogaoscore,
                                        testWholeDataRetest::setZuogaograde,
                                        testWholeDataRetest::setZuogaotime);

                                // 项目2只有值和时间
                                applyItemData(itemMap.get(2),
                                        testWholeDataRetest::setTizhongval,
                                        testWholeDataRetest::setTizhongtime);

                                applyItemData(itemMap.get(4),
                                        testWholeDataRetest::setTzzsval,
                                        testWholeDataRetest::setTzzsscore,
                                        testWholeDataRetest::setTzzsgrade,
                                        testWholeDataRetest::setTzzstime);

                                applyItemData(itemMap.get(8),
                                        testWholeDataRetest::setTzlval,
                                        testWholeDataRetest::setTzlscore,
                                        testWholeDataRetest::setTzlgrade,
                                        testWholeDataRetest::setTzltime);

                                // 项目5只有值和时间
                                applyItemData(itemMap.get(5),
                                        testWholeDataRetest::setXiongweival,
                                        testWholeDataRetest::setXiongweitime);

                                // 项目6只有值和时间
                                applyItemData(itemMap.get(6),
                                        testWholeDataRetest::setYaoweival,
                                        testWholeDataRetest::setYaoweitime);

                                applyItemData(itemMap.get(7),
                                        testWholeDataRetest::setTunweival,
                                        testWholeDataRetest::setTunweiscore,
                                        testWholeDataRetest::setTunweigrade,
                                        testWholeDataRetest::setTunweitime);

                                applyItemData(itemMap.get(9),
                                        testWholeDataRetest::setFhlval,
                                        testWholeDataRetest::setFhlscore,
                                        testWholeDataRetest::setFhlgrade,
                                        testWholeDataRetest::setFhltime);

                                applyItemData(itemMap.get(10),
                                        testWholeDataRetest::setGlcval,
                                        testWholeDataRetest::setGlcscore,
                                        testWholeDataRetest::setGlcgrade,
                                        testWholeDataRetest::setGlctime);

                                applyItemData(itemMap.get(11),
                                        testWholeDataRetest::setLfzydgttval,
                                        testWholeDataRetest::setLfzydgttscore,
                                        testWholeDataRetest::setLfzydgttgrade,
                                        testWholeDataRetest::setLfzydgtttime);

                                // 项目31只有值和时间
                                applyItemData(itemMap.get(31),
                                        testWholeDataRetest::setLfzydgttzval,
                                        testWholeDataRetest::setLfzydgttztime);

                                // 项目32只有值和时间
                                applyItemData(itemMap.get(32),
                                        testWholeDataRetest::setLfzydgttyval,
                                        testWholeDataRetest::setLfzydgttytime);

                                applyItemData(itemMap.get(12),
                                        testWholeDataRetest::setAjxlval,
                                        testWholeDataRetest::setAjxlscore,
                                        testWholeDataRetest::setAjxlgrade,
                                        testWholeDataRetest::setAjxltime);

                                applyItemData(itemMap.get(13),
                                        testWholeDataRetest::setWolival,
                                        testWholeDataRetest::setWoliscore,
                                        testWholeDataRetest::setWoligrade,
                                        testWholeDataRetest::setWolitime);

                                applyItemData(itemMap.get(14),
                                        testWholeDataRetest::setZongtiaoval,
                                        testWholeDataRetest::setZongtiaoscore,
                                        testWholeDataRetest::setZongtiaograde,
                                        testWholeDataRetest::setZongtiaotime);

                                applyItemData(itemMap.get(15),
                                        testWholeDataRetest::setFwcval,
                                        testWholeDataRetest::setFwcscore,
                                        testWholeDataRetest::setFwcgrade,
                                        testWholeDataRetest::setFwctime);

                                applyItemData(itemMap.get(16),
                                        testWholeDataRetest::setGwcval,
                                        testWholeDataRetest::setGwcscore,
                                        testWholeDataRetest::setGwcgrade,
                                        testWholeDataRetest::setGwctime);

                                applyItemData(itemMap.get(17),
                                        testWholeDataRetest::setYfzywqzval,
                                        testWholeDataRetest::setYfzywqzscore,
                                        testWholeDataRetest::setYfzywqzgrade,
                                        testWholeDataRetest::setYfzywqztime);

                                applyItemData(itemMap.get(18),
                                        testWholeDataRetest::setZwtqqval,
                                        testWholeDataRetest::setZwtqqscore,
                                        testWholeDataRetest::setZwtqqgrade,
                                        testWholeDataRetest::setZwtqqtime);

                                applyItemData(itemMap.get(19),
                                        testWholeDataRetest::setBydjzlval,
                                        testWholeDataRetest::setBydjzlscore,
                                        testWholeDataRetest::setBydjzlgrade,
                                        testWholeDataRetest::setBydjzltime);

                                applyItemData(itemMap.get(20),
                                        testWholeDataRetest::setXzfysval,
                                        testWholeDataRetest::setXzfysscore,
                                        testWholeDataRetest::setXzfysgrade,
                                        testWholeDataRetest::setXzfystime);

                                applyItemData(itemMap.get(21),
                                        testWholeDataRetest::setBeilival,
                                        testWholeDataRetest::setBeiliscore,
                                        testWholeDataRetest::setBeiligrade,
                                        testWholeDataRetest::setBeilitime);

                                applyItemData(itemMap.get(22),
                                        testWholeDataRetest::setSsmzzval,
                                        testWholeDataRetest::setSsmzzscore,
                                        testWholeDataRetest::setSsmzzgrade,
                                        testWholeDataRetest::setSsmzztime);

                                applyItemData(itemMap.get(23),
                                        testWholeDataRetest::setLdtyval,
                                        testWholeDataRetest::setLdtyscore,
                                        testWholeDataRetest::setLdtygrade,
                                        testWholeDataRetest::setLdtytime);

                                applyItemData(itemMap.get(24),
                                        testWholeDataRetest::setSjlxtval,
                                        testWholeDataRetest::setSjlxtscore,
                                        testWholeDataRetest::setSjlxtgrade,
                                        testWholeDataRetest::setSjlxttime);

                                applyItemData(itemMap.get(25),
                                        testWholeDataRetest::setSwmrzapval,
                                        testWholeDataRetest::setSwmrzapscore,
                                        testWholeDataRetest::setSwmrzapgrade,
                                        testWholeDataRetest::setSwmrzaptime);

                                // 特殊处理项目26
                                TestCorporeityDTO item26 = itemMap.get(26);
                                if (item26 != null) {
                                    testWholeDataRetest.setZphmval(toSafeFloat(item26.getTestValue()));
                                    testWholeDataRetest.setZphmscore(toSafeFloat(item26.getScore()));
                                    testWholeDataRetest.setZphmgrade(StringUtils.trimToEmpty(item26.getGrade()));
                                    testWholeDataRetest.setZphmtime(StringUtils.trimToEmpty(item26.getSpecificTime()));
                                    testWholeDataRetest.setZphmnb(item26.getValueOne() == null ? "" : item26.getValueOne().toString());
                                }

                                // 处理综合得分(100)
                                TestCorporeityDTO item100 = itemMap.get(100);
                                if (item100 != null) {
                                    if (StringUtils.isNotEmpty(item100.getScore().toString())) {
                                        testWholeDataRetest.setZonghescore(toSafeFloat(item100.getScore()));
                                        testWholeDataRetest.setZonghegrade(item100.getGrade());
                                    }
                                }

                                testWholeDataRetest.setIspassretest(1);
                                testWholeDataRetest.setType(1);

                                try {
                                    //查询该idcard,testtime的完整测试数据是否已经存在，存在更新，不存在插入,这里复测数据还是一个人，一天只能有一条记录，如果有多次复测记录会覆盖
                                    TestWholeDataRetest testWholeDataRetestTmp = testwholedataretestMapper.getByTableName(testWholeDataRetest, testWholeDataRetestTableName);
                                    if (null == testWholeDataRetestTmp) {
                                        testwholedataretestMapper.insertByTableName(testWholeDataRetest, testWholeDataRetestTableName);
                                    } else {
                                        testWholeDataRetest.setId(testWholeDataRetestTmp.getId());
                                        testwholedataretestMapper.updateByTableName(testWholeDataRetest, testWholeDataRetestTableName);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    messageMap.put("code", 400);
                                    messageMap.put("success", false);
                                    messageMap.put("message", e);
                                }
                            }

                        }
                        System.out.println("分表上传处理完成时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        messageMap.put("success", true);
                        messageMap.put("code", 200);
                        messageMap.put("message", msg);
                    }
                    else {
                        messageMap.put("success", true);
                        messageMap.put("code", 200);
                        messageMap.put("message", "没有数据");
                    }
                    return messageMap;
                }
            }else{
                messageMap.put("success", false);
                messageMap.put("code", 400);
                messageMap.put("message", "版本受限，请使用正确的软件测试");
                return messageMap;
            }

        }else{
            messageMap.put("success", false);
            messageMap.put("code", 400);
            messageMap.put("message", "token不存在");
            return messageMap;
        }
    }


    /**
     * 整表实时接收处理
     * @param membersData
     * @param msg
     * @return
     * */
    public TestWholeData getTestWholeData(MembersDataDTO membersData, StringBuilder msg) {
        TestWholeData testWholeData = new TestWholeData();
        //设置测试状态是已完成
        testWholeData.setStatus(1);
        testWholeData.setRealname(membersData.getName());
        testWholeData.setSex(membersData.getGender());
        testWholeData.setBirthdate(membersData.getBirthTime());
        testWholeData.setAge(toSafeFloat(membersData.getAge()));
        testWholeData.setIdcard(membersData.getIdNumber());
        testWholeData.setNation(StringUtils.trimToEmpty(membersData.getEthnicity()));
        testWholeData.setAddress(StringUtils.trimToEmpty(membersData.getHomeAddress()));
        testWholeData.setWorkunit(StringUtils.trimToEmpty(membersData.getWorkUnit()));
        testWholeData.setCreatetime(StringUtils.trimToEmpty(membersData.getRegistrationDate()));
        testWholeData.setUpdatetime(StringUtils.trimToEmpty(membersData.getUpdatetime()));
        testWholeData.setDeleted(StringUtils.trimToEmpty(membersData.getDeleted()));
        testWholeData.setPosition(StringUtils.trimToEmpty(membersData.getPosition()));
        testWholeData.setOccupation(StringUtils.trimToEmpty(membersData.getOccupation()));
        testWholeData.setIndustry(StringUtils.trimToEmpty(membersData.getIndustry()));
        testWholeData.setTowncountry(StringUtils.trimToEmpty(membersData.getTownAndCountry()));
        testWholeData.setCulture(StringUtils.trimToEmpty(membersData.getLevelOfEducation()));
        testWholeData.setPhone(StringUtils.trimToEmpty(membersData.getPhoneNumber()));
        testWholeData.setMechanismname(StringUtils.trimToEmpty(membersData.getInstitutionName()));
        testWholeData.setMechanismcode(StringUtils.trimToEmpty(membersData.getInstitutionCode()));
        testWholeData.setInstrumentManufacturer(membersData.getInstrumentManufacturer());
        testWholeData.setTestage(toSafeFloat(membersData.getTestAge()));
        testWholeData.setTesttime(membersData.getTestDate());
        testWholeData.setTestmonth(truncateToMonthWithoutZeroPadFast(membersData.getTestDate()));
        testWholeData.setShengaoval(toSafeFloat(membersData.getHeight()));
        testWholeData.setShengaoscore(toSafeFloat(membersData.getHeightScore()));
        testWholeData.setShengaograde(StringUtils.trimToEmpty(membersData.getHeightAssessment()));
        testWholeData.setShengaotime(StringUtils.trimToEmpty(membersData.getDateOfHeightTest()));
        testWholeData.setShengaogps(StringUtils.trimToEmpty(membersData.getHeightGPS()));
        testWholeData.setZuogaoval(toSafeFloat(membersData.getSitUpHeight()));
        testWholeData.setZuogaoscore(toSafeFloat(membersData.getSitUpHeightScore()));
        testWholeData.setZuogaograde(StringUtils.trimToEmpty(membersData.getSitUpHeightAssessment()));
        testWholeData.setZuogaotime(StringUtils.trimToEmpty(membersData.getDateOfSitUpHeightTest()));
        testWholeData.setZuogaogps(StringUtils.trimToEmpty(membersData.getSitUpHeightGPS()));
        testWholeData.setTizhongval(toSafeFloat(membersData.getWeight()));
        testWholeData.setTizhongtime(StringUtils.trimToEmpty(membersData.getDateOfWeightTest()));
        testWholeData.setTizhonggps(StringUtils.trimToEmpty(membersData.getWeightGps()));
        testWholeData.setTzzsval(toSafeFloat(membersData.getBodyMassIndex()));
        testWholeData.setTzzsscore(toSafeFloat(membersData.getBmIScore()));
        testWholeData.setTzzsgrade(StringUtils.trimToEmpty(membersData.getBmiAssessment()));
        testWholeData.setTzzstime(StringUtils.trimToEmpty(membersData.getDateOfBMITest()));
        testWholeData.setTzzsgps(StringUtils.trimToEmpty(membersData.getBmiGPS()));
        testWholeData.setTzlval(toSafeFloat(membersData.getBodyFatRate()));
        testWholeData.setTzlscore(toSafeFloat(membersData.getBodyFatRateScore()));
        testWholeData.setTzlgrade(StringUtils.trimToEmpty(membersData.getBodyFatRateAssessment()));
        testWholeData.setTzltime(StringUtils.trimToEmpty(membersData.getDateOfBodyFatRateTest()));
        testWholeData.setTzlgps(StringUtils.trimToEmpty(membersData.getBodyFatRateGPS()));
        testWholeData.setXiongweival(toSafeFloat(membersData.getChestCircumference()));
        testWholeData.setXiongweiscore(toSafeFloat(membersData.getChestCircumferenceScore()));
        testWholeData.setXiongweigrade(StringUtils.trimToEmpty(membersData.getChestCircumferenceAssessment()));
        testWholeData.setXiongweitime(StringUtils.trimToEmpty(membersData.getDateOfChestCircumferenceTest()));
        testWholeData.setXiongweigps(StringUtils.trimToEmpty(membersData.getChestCircumferenceGPS()));
        testWholeData.setYaoweival(toSafeFloat(membersData.getWaist()));
        testWholeData.setYaoweitime(StringUtils.trimToEmpty(membersData.getDateOfWaistTest()));
        testWholeData.setYaoweigps(StringUtils.trimToEmpty(membersData.getWaistGPS()));
        testWholeData.setTunweival(toSafeFloat(membersData.getHip()));
        testWholeData.setTunweitime(StringUtils.trimToEmpty(membersData.getDateOfHipTest()));
        testWholeData.setTunweigps(StringUtils.trimToEmpty(membersData.getHipGPS()));
        testWholeData.setFhlval(toSafeFloat(membersData.getVitalCapacity()));
        testWholeData.setFhlscore(toSafeFloat(membersData.getVitalCapacityScore()));
        testWholeData.setFhlgrade(StringUtils.trimToEmpty(membersData.getVitalCapacityAssessment()));
        testWholeData.setFhltime(StringUtils.trimToEmpty(membersData.getDateOfVitalCapacityTest()));
        testWholeData.setFhlgps(StringUtils.trimToEmpty(membersData.getVitalCapacityGPS()));
        testWholeData.setGlcval(toSafeFloat(membersData.getRelativeValuesOfTheSecondLevelLoadTestOnAPowerBike()));
        testWholeData.setGlcscore(toSafeFloat(membersData.getSecondLevelLoadTestOnAPowerBikeScore()));
        testWholeData.setGlcgrade(StringUtils.trimToEmpty(membersData.getSecondLevelLoadTestOnAPowerBikeAssessment()));
        testWholeData.setGlctime(StringUtils.trimToEmpty(membersData.getDateOfSecondLevelLoadTestOnAPowerBike()));
        testWholeData.setGlcgps(StringUtils.trimToEmpty(membersData.getSecondLevelLoadTestOnAPowerBikeGPS()));
        testWholeData.setLfzydgttval(toSafeFloat(membersData.getMinute2LegRaisesInPlace()));
        testWholeData.setLfzydgttscore(toSafeFloat(membersData.getMinute2LegRaisesInPlaceScore()));
        testWholeData.setLfzydgttgrade(StringUtils.trimToEmpty(membersData.getMinute2LegRaisesInPlaceAssessment()));
        testWholeData.setLfzydgtttime(StringUtils.trimToEmpty(membersData.getEndOfMinute2LegRaisesInPlaceTest()));
        testWholeData.setLfzydgttgps(StringUtils.trimToEmpty(membersData.getMinute2LegRaisesInPlaceGPS()));
        testWholeData.setLfzydgttzval(toSafeFloat(membersData.getMinute2LegRaisesInPlaceLeftLeg()));
        testWholeData.setLfzydgttztime(StringUtils.trimToEmpty(membersData.getDateOfMinute2LegRaisesInPlaceLeftLeg()));
        testWholeData.setLfzydgttyval(toSafeFloat(membersData.getMinute2LegRaisesInPlaceRightLeg()));
        testWholeData.setLfzydgttytime(StringUtils.trimToEmpty(membersData.getDateOfMinute2LegRaisesInPlaceRightLegTest()));
        testWholeData.setAjxlval(toSafeFloat(membersData.getRestingHeartRate()));
        testWholeData.setAjxltime(StringUtils.trimToEmpty(membersData.getDateOfRestingHeartRate()));
        testWholeData.setAjxlgps(StringUtils.trimToEmpty(membersData.getRestingHeartRateGPS()));
        testWholeData.setWolival(toSafeFloat(membersData.getGripStrength()));
        testWholeData.setWoliscore(toSafeFloat(membersData.getGripStrengthScore()));
        testWholeData.setWoligrade(StringUtils.trimToEmpty(membersData.getGripStrengthAssessment()));
        testWholeData.setWolitime(StringUtils.trimToEmpty(membersData.getDateOfGripStrengthTest()));
        testWholeData.setWoligps(StringUtils.trimToEmpty(membersData.getGripStrengthGPS()));
        testWholeData.setZongtiaoval(toSafeFloat(membersData.getVerticalJump()));
        testWholeData.setZongtiaoscore(toSafeFloat(membersData.getVerticalJumpScore()));
        testWholeData.setZongtiaograde(StringUtils.trimToEmpty(membersData.getVerticalJumpAssessment()));
        testWholeData.setZongtiaotime(StringUtils.trimToEmpty(membersData.getDateOfVerticalJumpTest()));
        testWholeData.setZongtiaogps(StringUtils.trimToEmpty(membersData.getVerticalJumpGPS()));
        testWholeData.setFwcval(toSafeFloat(membersData.getPushUp()));
        testWholeData.setFwcscore(toSafeFloat(membersData.getPushUpScore()));
        testWholeData.setFwcgrade(StringUtils.trimToEmpty(membersData.getPushUpAssessment()));
        testWholeData.setFwctime(StringUtils.trimToEmpty(membersData.getDateOfPushUpTest()));
        testWholeData.setFwcgps(StringUtils.trimToEmpty(membersData.getPushUpGPS()));
        testWholeData.setGwcval(toSafeFloat(membersData.getKneelingPushUp()));
        testWholeData.setGwcscore(toSafeFloat(membersData.getKneelingPushUpScore()));
        testWholeData.setGwcgrade(StringUtils.trimToEmpty(membersData.getKneelingPushUpAssessment()));
        testWholeData.setGwctime(StringUtils.trimToEmpty(membersData.getDateOfKneelingPushUpTest()));
        testWholeData.setGwcgps(StringUtils.trimToEmpty(membersData.getKneelingPushUpGPS()));
        testWholeData.setYfzywqzval(toSafeFloat(membersData.getMinute1SitUps()));
        testWholeData.setYfzywqzscore(toSafeFloat(membersData.getMinute1SitUpsScore()));
        testWholeData.setYfzywqzgrade(StringUtils.trimToEmpty(membersData.getMinute1SitUpsAssessment()));
        testWholeData.setYfzywqztime(StringUtils.trimToEmpty(membersData.getDateOfMinute1SitUpsTest()));
        testWholeData.setYfzywqzgps(StringUtils.trimToEmpty(membersData.getMinute1SitUpsGPS()));
        testWholeData.setZwtqqval(toSafeFloat(membersData.getSeatedForwardBending()));
        testWholeData.setZwtqqscore(toSafeFloat(membersData.getSeatedForwardBendingScore()));
        testWholeData.setZwtqqgrade(StringUtils.trimToEmpty(membersData.getSeatedForwardBendingAssessment()));
        testWholeData.setZwtqqtime(StringUtils.trimToEmpty(membersData.getDateOfSeatedForwardBendingTest()));
        testWholeData.setZwtqqgps(StringUtils.trimToEmpty(membersData.getSeatedForwardBendingGPS()));
        testWholeData.setBydjzlval(toSafeFloat(membersData.getEyesClosedOneLeggedStand()));
        testWholeData.setBydjzlscore(toSafeFloat(membersData.getEyesClosedOneLeggedStandScore()));
        testWholeData.setBydjzlgrade(StringUtils.trimToEmpty(membersData.getEyesClosedOneLeggedStandAssessment()));
        testWholeData.setBydjzltime(StringUtils.trimToEmpty(membersData.getDateOfEyesClosedOnLeggedStandTest()));
        testWholeData.setBydjzlgps(StringUtils.trimToEmpty(membersData.getEyesClosedOneLeggedStandGPS()));
        testWholeData.setXzfysval(toSafeFloat(membersData.getSelectionReactionTime()));
        testWholeData.setXzfysscore(toSafeFloat(membersData.getSelectionReactionTimeScore()));
        testWholeData.setXzfysgrade(StringUtils.trimToEmpty(membersData.getSelectionReactionTimeAssessment()));
        testWholeData.setXzfystime(StringUtils.trimToEmpty(membersData.getDateOfSelectionReactionTimeTest()));
        testWholeData.setXzfysgps(StringUtils.trimToEmpty(membersData.getSelectionReactionTimeGPS()));
        testWholeData.setBeilival(toSafeFloat(membersData.getBackStrength()));
        testWholeData.setBeilitime(StringUtils.trimToEmpty(membersData.getDateOfBackStrengthTest()));
        testWholeData.setBeiligps(StringUtils.trimToEmpty(membersData.getBackStrengthGPS()));
        testWholeData.setSsmzzval(toSafeFloat(membersData.getSeconds30SittingAndStanding()));
        testWholeData.setSsmzzscore(toSafeFloat(membersData.getSeconds30SittingAndStandingScore()));
        testWholeData.setSsmzzgrade(StringUtils.trimToEmpty(membersData.getSeconds30SittingAndStandingAssessment()));
        testWholeData.setSsmzztime(StringUtils.trimToEmpty(membersData.getDateOfSeconds30SittingAndStandingTest()));
        testWholeData.setSsmzzgps(StringUtils.trimToEmpty(membersData.getSeconds30SittingAndStandingGPS()));
        testWholeData.setLdtyval(toSafeFloat(membersData.getStandingLongJump()));
        testWholeData.setLdtyscore(toSafeFloat(membersData.getStandingLongJumpScore()));
        testWholeData.setLdtygrade(StringUtils.trimToEmpty(membersData.getStandingLongJumpAssessment()));
        testWholeData.setLdtytime(StringUtils.trimToEmpty(membersData.getDateOfStandingLongJumpTest()));
        testWholeData.setLdtygps(StringUtils.trimToEmpty(membersData.getStandingLongJumpGPS()));
        testWholeData.setSjlxtval(toSafeFloat(membersData.getContinuousJumpsOnBothFeet()));
        testWholeData.setSjlxtscore(toSafeFloat(membersData.getContinuousJumpsOnBothFeetScore()));
        testWholeData.setSjlxtgrade(StringUtils.trimToEmpty(membersData.getContinuousJumpsOnBothFeetAssessment()));
        testWholeData.setSjlxttime(StringUtils.trimToEmpty(membersData.getDateOfContinuousJumpsOnBothFeetTest()));
        testWholeData.setSjlxtgps(StringUtils.trimToEmpty(membersData.getContinuousJumpsOnBothFeetGPS()));
        testWholeData.setSwmrzapval(toSafeFloat(membersData.getMeter15RunAroundObstacles()));
        testWholeData.setSwmrzapscore(toSafeFloat(membersData.getMeter15RunAroundObstaclesScore()));
        testWholeData.setSwmrzapgrade(StringUtils.trimToEmpty(membersData.getMeter15RunAroundObstaclesAssessment()));
        testWholeData.setSwmrzaptime(StringUtils.trimToEmpty(membersData.getDateOfMeter15RunAroundObstaclesTest()));
        testWholeData.setSwmrzapgps(StringUtils.trimToEmpty(membersData.getMeter15RunAroundObstaclesGPS()));
        testWholeData.setZphmval(toSafeFloat(membersData.getWalkingOnABalanceBeam()));
        testWholeData.setZphmscore(toSafeFloat(membersData.getWalkingSidewaysOnABalanceBeamScore()));
        testWholeData.setZphmgrade(StringUtils.trimToEmpty(membersData.getWalkingSidewaysOnABalanceBeamAssessment()));
        testWholeData.setZphmtime(StringUtils.trimToEmpty(membersData.getDateOfWalkingSidewaysOnABalanceBeamTest()));
        testWholeData.setZphmgps(StringUtils.trimToEmpty(membersData.getWalkingSidewaysOnABalanceBeamGPS()));
        testWholeData.setZphmnb(membersData.getWalkingSidewaysOnABalanceBeam()==null?"":membersData.getWalkingSidewaysOnABalanceBeam().toString());
        if (membersData.getNationalPhysicalFitnessCompositeScore()==null) {
            //该会员没有综合得分，表明该会员参与评价的指标未测试完，测试状态是未完成
            testWholeData.setStatus(0);
        } else {
            //综合得分不为空，表明参与评价的指标测试完成
            testWholeData.setZonghescore(toSafeFloat(membersData.getNationalPhysicalFitnessCompositeScore()));
            testWholeData.setZonghegrade(membersData.getNationalPhysicalFitnessCompositeAssessment());
        }
        testWholeData.setMetval(toSafeFloat(membersData.getMetValue()));
        testWholeData.setRelativeval(toSafeFloat(membersData.getRelativeValuesOfTheSecondLevelLoadTestOnAPowerBike()));
        testWholeData.setAbsoluteval(toSafeFloat(membersData.getAbsoluteValuesOfTheSecondLevelLoadTestOnAPowerBike()));
        String glcHeartRate = joinDoubles(",",membersData.getQuietHeartRate(),
                membersData.getEndOfWarmUpPeriodHeartRate(),
                membersData.getHeartRateAfter60Seconds(),
                membersData.getHeartRateAfter90Seconds(),
                membersData.getHeartRateAfter120Seconds(),
                membersData.getHeartRateAfter150Seconds(),
                membersData.getHeartRateAfter180Seconds(),
                membersData.getEndOfTheFirstLevelLoadHeartRate(),
                membersData.getHeartRateAfter240Seconds(),
                membersData.getHeartRateAfter270Seconds(),
                membersData.getHeartRateAfter300Seconds(),
                membersData.getHeartRateAfter330Seconds(),
                membersData.getHeartRateAfter360Seconds(),
                membersData.getEndOfTheSecondLevelLoadHeartRate(),
                membersData.getEndOfRecoveryPeriodHeartRate());
        testWholeData.setGlcHeartRate(glcHeartRate);
        testWholeData.setGlcspecifictime(StringUtils.trimToEmpty(membersData.getDateOfSecondLevelLoadTestOnAPowerBike()));
        testWholeData.setGlctablegps(StringUtils.trimToEmpty(membersData.getSecondLevelLoadTestOnAPowerBikeGPS()));
        if (membersData.getRestingBloodPressureRestingPulse()==null) {
            //该会员没有心率，表明该会员没有测试血压计，判断是否是幼儿，如果不是幼儿，则该会员测试未完成
            if (isAgeAboveThreshold(membersData.getTestAge(), 20.0f)) {
                testWholeData.setStatus(0);
            }
        } else {
            //心率不为空，表明该会员测试了血压计
            testWholeData.setHeartrate(membersData.getRestingBloodPressureRestingPulse());
            testWholeData.setDiastolicpressure(membersData.getRestingBloodPressureDiastolic());
            testWholeData.setSystolicpressure(membersData.getRestingBloodPressureSystolic());
            testWholeData.setXyjspecifictime(StringUtils.trimToEmpty(membersData.getDateOfRestingBloodPressureTest()));
            testWholeData.setXyjgps(StringUtils.trimToEmpty(membersData.getRestingBloodPressureGPS()));
        }
        testWholeData.setShengao(membersData.getHeight()==null?"":membersData.getHeight().toString());
        testWholeData.setTizhong(membersData.getWeight()==null?"":membersData.getWeight().toString());
        testWholeData.setK1Zongzukang(membersData.getTotalImpedanceAt1kHz()==null?"":membersData.getTotalImpedanceAt1kHz().toString());
        testWholeData.setK5Zongzukang(membersData.getTotalImpedanceAt5kHz()==null?"":membersData.getTotalImpedanceAt5kHz().toString());
        testWholeData.setK20Zongzukang(membersData.getTotalImpedanceAt20kHz()==null?"":membersData.getTotalImpedanceAt20kHz().toString());
        testWholeData.setK50Zongzukang(membersData.getTotalImpedanceAt50kHz()==null?"":membersData.getTotalImpedanceAt50kHz().toString());
        testWholeData.setK50Xiangweicha(membersData.getK50_XIANGWEICHA()==null?"":membersData.getK50_XIANGWEICHA().toString());
        testWholeData.setK50Zuoshangzhizukang(membersData.getLeftUpperLimbImpedance()==null?"":membersData.getLeftUpperLimbImpedance().toString());
        testWholeData.setK50Youshangzhizukang(membersData.getRightUpperLimbImpedance()==null?"":membersData.getRightUpperLimbImpedance().toString());
        testWholeData.setK50Quganzukang(membersData.getTrunkImpedance()==null?"":membersData.getTrunkImpedance().toString());
        testWholeData.setK50Zuoxiazhizukang(membersData.getLeftLowerLimbImpedance()==null?"":membersData.getLeftLowerLimbImpedance().toString());
        testWholeData.setK50Youxiazhizukang(membersData.getRightUpperLimbImpedance()==null?"":membersData.getRightUpperLimbImpedance().toString());
        testWholeData.setK100Zongzukang(membersData.getTotalImpedanceAt100kHz()==null?"":membersData.getTotalImpedanceAt100kHz().toString());
        testWholeData.setK250Zongzukang(membersData.getTotalImpedanceAt250kHz()==null?"":membersData.getTotalImpedanceAt250kHz().toString());
        testWholeData.setK500Zongzukang(membersData.getTotalImpedanceAt500kHz()==null?"":membersData.getTotalImpedanceAt500kHz().toString());
        testWholeData.setK1000Zongzukang(membersData.getTotalImpedanceAt1000kHz()==null?"":membersData.getTotalImpedanceAt1000kHz().toString());
        testWholeData.setBztzBiaozhunzhi(membersData.getBZTZ_BIAOZHUNZHI()==null?"":membersData.getBZTZ_BIAOZHUNZHI().toString());
        testWholeData.setBztzXiajie(membersData.getBZTZ_XIAJIE()==null?"":membersData.getBZTZ_XIAJIE().toString());
        testWholeData.setBztzShangjie(membersData.getBZTZ_SHANGJIE()==null?"":membersData.getBZTZ_SHANGJIE().toString());
        testWholeData.setQztzShicezhi(membersData.getMeasuredLeanBodyMass()==null?"":membersData.getMeasuredLeanBodyMass().toString());
        testWholeData.setQztzXiajie(membersData.getQZTZ_XIAJIE()==null?"":membersData.getQZTZ_XIAJIE().toString());
        testWholeData.setQztzShangjie(membersData.getQZTZ_SHANGJIE()==null?"":membersData.getQZTZ_SHANGJIE().toString());
        testWholeData.setTzflShicezhi(membersData.getMeasuredBodyFatMass()==null?"":membersData.getMeasuredBodyFatMass().toString());
        testWholeData.setTzflXiajie(membersData.getTZFL_XIAJIE()==null?"":membersData.getTZFL_XIAJIE().toString());
        testWholeData.setTzflShangjie(membersData.getTZFL_SHANGJIE()==null?"":membersData.getTZFL_SHANGJIE().toString());
        testWholeData.setStjrlShicezhi(membersData.getMeasuredTotalBodyWater()==null?"":membersData.getMeasuredTotalBodyWater().toString());
        testWholeData.setStjrlXiajie(membersData.getSTJRL_XIAJIE()==null?"":membersData.getSTJRL_XIAJIE().toString());
        testWholeData.setStjrlShangjie(membersData.getSTJRL_SHANGJIE()==null?"":membersData.getSTJRL_SHANGJIE().toString());
        testWholeData.setGgjrShicezhi(membersData.getMeasuredSkeletalMuscleMass()==null?"":membersData.getMeasuredSkeletalMuscleMass().toString());
        testWholeData.setGgjrXiajie(membersData.getGGJR_XIAJIE()==null?"":membersData.getGGJR_XIAJIE().toString());
        testWholeData.setGgjrShangjie(membersData.getGGJR_SHANGJIE()==null?"":membersData.getGGJR_SHANGJIE().toString());
        testWholeData.setStzsfShicezhi(membersData.getMeasuredTotalBodyWater()==null?"":membersData.getMeasuredTotalBodyWater().toString());
        testWholeData.setStzsfXiajie(membersData.getSTZSF_XIAJIE()==null?"":membersData.getSTZSF_XIAJIE().toString());
        testWholeData.setStzsfShangjie(membersData.getSTZSF_SHANGJIE()==null?"":membersData.getSTZSF_SHANGJIE().toString());
        testWholeData.setDbzShicezhi(membersData.getMeasuredProteinMass()==null?"":membersData.getMeasuredProteinMass().toString());
        testWholeData.setDbzXiajie(membersData.getDBZ_XIAJIE()==null?"":membersData.getDBZ_XIAJIE().toString());
        testWholeData.setDbzShangjie(membersData.getDBZ_SHANGJIE()==null?"":membersData.getDBZ_SHANGJIE().toString());
        testWholeData.setWjyShicezhi(membersData.getMeasuredMineralMass()==null?"":membersData.getMeasuredMineralMass().toString());
        testWholeData.setWjyXiajie(membersData.getWJY_XIAJIE()==null?"":membersData.getWJY_XIAJIE().toString());
        testWholeData.setWjyShangjie(membersData.getWJY_SHANGJIE()==null?"":membersData.getWJY_SHANGJIE().toString());
        testWholeData.setXbwyShicezhi(membersData.getMeasuredExtracellularFluid()==null?"":membersData.getMeasuredExtracellularFluid().toString());
        testWholeData.setXbwyXiajie(membersData.getXBWY_XIAJIE()==null?"":membersData.getXBWY_XIAJIE().toString());
        testWholeData.setXbwyShangjie(membersData.getXBWY_SHANGJIE()==null?"":membersData.getXBWY_SHANGJIE().toString());
        testWholeData.setXbnyShicezhi(membersData.getMeasuredIntracellularFluid()==null?"":membersData.getMeasuredIntracellularFluid().toString());
        testWholeData.setXbnyXiajie(membersData.getXBNY_XIAJIE()==null?"":membersData.getXBNY_XIAJIE().toString());
        testWholeData.setXbnyShangjie(membersData.getXBNY_SHANGJIE()==null?"":membersData.getXBNY_SHANGJIE().toString());
        testWholeData.setZszjrlShicezhi(membersData.getMeasuredLeftUpperLimbMuscleMass()==null?"":membersData.getMeasuredLeftUpperLimbMuscleMass().toString());
        testWholeData.setZszjrlXiajie(membersData.getZSZJRL_XIAJIE()==null?"":membersData.getZSZJRL_XIAJIE().toString());
        testWholeData.setZszjrlShangjie(membersData.getZSZJRL_SHANGJIE()==null?"":membersData.getZSZJRL_SHANGJIE().toString());
        testWholeData.setYszjrlShicezhi(membersData.getMeasuredRightUpperLimbMuscleMass()==null?"":membersData.getMeasuredRightUpperLimbMuscleMass().toString());
        testWholeData.setYszjrlXiajie(membersData.getYSZJRL_XIAJIE()==null?"":membersData.getYSZJRL_XIAJIE().toString());
        testWholeData.setYszjrlShangjie(membersData.getYSZJRL_SHANGJIE()==null?"":membersData.getYSZJRL_SHANGJIE().toString());
        testWholeData.setQgjrlShicezhi(membersData.getMeasuredTrunkMuscleMass()==null?"":membersData.getMeasuredTrunkMuscleMass().toString());
        testWholeData.setQgjrlXiajie(membersData.getQGJRL_XIAJIE()==null?"":membersData.getQGJRL_XIAJIE().toString());
        testWholeData.setQgjrlShangjie(membersData.getQGJRL_SHANGJIE()==null?"":membersData.getQGJRL_SHANGJIE().toString());
        testWholeData.setZxzjrlShicezhi(membersData.getMeasuredLeftLowerLimbMuscleMass()==null?"":membersData.getMeasuredLeftLowerLimbMuscleMass().toString());
        testWholeData.setZxzjrlXiajie(membersData.getZXZJRL_XIAJIE()==null?"":membersData.getZXZJRL_XIAJIE().toString());
        testWholeData.setZxzjrlShangjie(membersData.getZXZJRL_SHANGJIE()==null?"":membersData.getZXZJRL_SHANGJIE().toString());
        testWholeData.setYxzjrlShicezhi(membersData.getMeasuredRightLowerLimbMuscleMass()==null?"":membersData.getMeasuredRightLowerLimbMuscleMass().toString());
        testWholeData.setYxzjrlXiajie(membersData.getYXZJRL_XIAJIE()==null?"":membersData.getYXZJRL_XIAJIE().toString());
        testWholeData.setYxzjrlShangjie(membersData.getYXZJRL_SHANGJIE()==null?"":membersData.getYXZJRL_SHANGJIE().toString());
        testWholeData.setZszzflShicezhi(membersData.getMeasuredLeftUpperLimbFatMass()==null?"":membersData.getMeasuredLeftUpperLimbFatMass().toString());
        testWholeData.setZszzflXiajie(membersData.getZSZZFL_XIAJIE()==null?"":membersData.getZSZZFL_XIAJIE().toString());
        testWholeData.setZszzflShangjie(membersData.getZSZZFL_SHANGJIE()==null?"":membersData.getZSZZFL_SHANGJIE().toString());
        testWholeData.setYszzflShicezhi(membersData.getMeasuredRightUpperLimbFatMass()==null?"":membersData.getMeasuredRightUpperLimbFatMass().toString());
        testWholeData.setYszzflXiajie(membersData.getYSZZFL_XIAJIE()==null?"":membersData.getYSZZFL_XIAJIE().toString());
        testWholeData.setYszzflShangjie(membersData.getYSZZFL_SHANGJIE()==null?"":membersData.getYSZZFL_SHANGJIE().toString());
        testWholeData.setQgzflShicezhi(membersData.getMeasuredTrunkFatMass()==null?"":membersData.getMeasuredTrunkFatMass().toString());
        testWholeData.setQgzflXiajie(membersData.getQGZFL_XIAJIE()==null?"":membersData.getQGZFL_XIAJIE().toString());
        testWholeData.setQgzflShangjie(membersData.getQGZFL_SHANGJIE()==null?"":membersData.getQGZFL_SHANGJIE().toString());
        testWholeData.setZxzzflShicezhi(membersData.getMeasuredLeftLowerLimbFatMass()==null?"":membersData.getMeasuredLeftLowerLimbFatMass().toString());
        testWholeData.setZxzzflXiajie(membersData.getZXZZFL_XIAJIE()==null?"":membersData.getZXZZFL_XIAJIE().toString());
        testWholeData.setZxzzflShangjie(membersData.getZXZZFL_SHANGJIE()==null?"":membersData.getZXZZFL_SHANGJIE().toString());
        testWholeData.setYxzzflShicezhi(membersData.getMeasuredRightLowerLimbFatMass()==null?"":membersData.getMeasuredRightLowerLimbFatMass().toString());
        testWholeData.setYxzzflXiajie(membersData.getYXZZFL_XIAJIE()==null?"":membersData.getYXZZFL_XIAJIE().toString());
        testWholeData.setYxzzflShangjie(membersData.getYXZZFL_SHANGJIE()==null?"":membersData.getYXZZFL_SHANGJIE().toString());
        testWholeData.setNzzfShicezhi(membersData.getMeasuredVisceralFatMass()==null?"":membersData.getMeasuredVisceralFatMass().toString());
        testWholeData.setTzjgShijizhi(membersData.getTZJG_SHIJIZHI()==null?"":membersData.getTZJG_SHIJIZHI().toString());
        testWholeData.setTzjgXiajie(membersData.getTZJG_XIAJIE()==null?"":membersData.getTZJG_XIAJIE().toString());
        testWholeData.setTzjgShangjie(membersData.getTZJG_SHANGJIE()==null?"":membersData.getTZJG_SHANGJIE().toString());
        testWholeData.setBmiShicezhi(membersData.getMeasuredBMI()==null?"":membersData.getMeasuredBMI().toString());
        testWholeData.setBmiXiajie(membersData.getBMI_XIAJIE()==null?"":membersData.getBMI_XIAJIE().toString());
        testWholeData.setBmiShangjie(membersData.getBMI_SHANGJIE()==null?"":membersData.getBMI_SHANGJIE().toString());
        testWholeData.setZfljgFatW(membersData.getMeasuredBodyFatPercentage()==null?"":membersData.getMeasuredBodyFatPercentage().toString());
        testWholeData.setZfljgXiajie(membersData.getZFLJG_XIAJIE()==null?"":membersData.getZFLJG_XIAJIE().toString());
        testWholeData.setZfljgShangjie(membersData.getZFLJG_SHANGJIE()==null?"":membersData.getZFLJG_SHANGJIE().toString());
        testWholeData.setJrjgShijizhi(membersData.getJRJG_SHIJIZHI()==null?"":membersData.getJRJG_SHIJIZHI().toString());
        testWholeData.setStzsfjgShijizhi(membersData.getSTZSFJG_SHIJIZHI()==null?"":membersData.getSTZSFJG_SHIJIZHI().toString());
        testWholeData.setDbzjgShijizhi(membersData.getDBZJG_SHIJIZHI()==null?"":membersData.getDBZJG_SHIJIZHI().toString());
        testWholeData.setWjyjgShijizhi(membersData.getWJYJG_SHIJIZHI()==null?"":membersData.getWJYJG_SHIJIZHI().toString());
        testWholeData.setYtbShicezhi(membersData.getYTB_SHICEZHI()==null?"":membersData.getYTB_SHICEZHI().toString());
        testWholeData.setYtbXiajie(membersData.getYTB_XIAJIE()==null?"":membersData.getYTB_XIAJIE().toString());
        testWholeData.setYtbShangjie(membersData.getYTB_SHANGJIE()==null?"":membersData.getYTB_SHANGJIE().toString());
        testWholeData.setFzxsShicezhi(membersData.getMeasuredEdemaCoefficient()==null?"":membersData.getMeasuredEdemaCoefficient().toString());
        testWholeData.setFzxsXiajie(membersData.getFZXS_XIAJIE()==null?"":membersData.getFZXS_XIAJIE().toString());
        testWholeData.setFzxsShangjie(membersData.getFZXS_SHANGJIE()==null?"":membersData.getFZXS_SHANGJIE().toString());
        testWholeData.setJhfxShangzhi(membersData.getJHFX_SHANGZHI()==null?"":membersData.getJHFX_SHANGZHI().toString());
        testWholeData.setJhfxXiazhi(membersData.getJHFX_XIAZHI()==null?"":membersData.getJHFX_XIAZHI().toString());
        testWholeData.setStllfxShangzhi(membersData.getSTLLFX_SHANGZHI()==null?"":membersData.getSTLLFX_SHANGZHI().toString());
        testWholeData.setStllfxXiazhi(membersData.getSTLLFX_XIAZHI()==null?"":membersData.getSTLLFX_XIAZHI().toString());
        testWholeData.setStllfxJirou(membersData.getSTLLFX_JIROU()==null?"":membersData.getSTLLFX_JIROU().toString());
        testWholeData.setShentinianling(membersData.getSHENTINIANLING()==null?"":membersData.getSHENTINIANLING().toString());
        testWholeData.setTizhongtiaojie(membersData.getTIZHONGTIAOJIE()==null?"":membersData.getTIZHONGTIAOJIE().toString());
        testWholeData.setZhifangtiaojie(membersData.getZHIFANGTIAOJIE()==null?"":membersData.getZHIFANGTIAOJIE().toString());
        testWholeData.setJiroutiaojie(membersData.getJIROUTIAOJIE()==null?"":membersData.getJIROUTIAOJIE().toString());
        testWholeData.setDxJichudaixie(membersData.getDX_JICHUDAIXIE()==null?"":membersData.getDX_JICHUDAIXIE().toString());
        testWholeData.setDxZongnengliangxiaohao(membersData.getDX_ZONGNENGLIANGXIAOHAO()==null?"":membersData.getDX_ZONGNENGLIANGXIAOHAO().toString());
        testWholeData.setFbzfShicezhi(membersData.getFBZF_SHICEZHI()==null?"":membersData.getFBZF_SHICEZHI().toString());
        testWholeData.setPostureone(membersData.getPosture_one());
        testWholeData.setPosturetwo(membersData.getPosture_two());
        testWholeData.setScore(membersData.getBodyFatRateScore() == null ? "":membersData.getBodyFatRateScore().toString());
        testWholeData.setTzlspecifictime(StringUtils.trimToEmpty(membersData.getDateOfBodyFatRateTest()));
        testWholeData.setTzltablegps(StringUtils.trimToEmpty(membersData.getBodyFatRateGPS()));
        //是否国测
        testWholeData.setType(1);
        //该会员完成测试进行质量筛查，未完成不进行质量筛查
        if (1 == testWholeData.getStatus()) {
            //是否筛查通过，一个人的各项指标质量筛查结果monitorData
            List<MonitorDataDTO> monitorData = unionscreeningMapper.getMonitorResult(testWholeData);
            //查出所有人群类型（幼儿，成年人，老年人），按照人群类型进行逻辑筛查
            List<TPeopleType> peopleTypeList = peopleTypeMapper.getAllList();
            for (TPeopleType tPeopleType : peopleTypeList) {
                if (testWholeData.getTestage() >= tPeopleType.getPeopleagemin() && testWholeData.getTestage() < tPeopleType.getPeopleagemax()) {
                    //返回这个人各指标详细的逻辑筛查不通过信息，
                    String message = "";
                    StringBuilder messageBuilder = new StringBuilder();
                    if (monitorData != null && !monitorData.isEmpty()) {
                        // 确保第一个元素存在
                        MonitorDataDTO peopledata = monitorData.get(0);
                        if (tPeopleType.getId()==1) {

                            // 使用辅助方法判断各字段
                            appendIfZero(messageBuilder, peopledata.getShengao(), "身高");
                            appendIfZero(messageBuilder, peopledata.getZuogao(), "坐高");
                            appendIfZero(messageBuilder, peopledata.getTizhong(), "体重");
                            appendIfZero(messageBuilder, peopledata.getXiongwei(), "胸围");
                            appendIfZero(messageBuilder, peopledata.getTzl(), "体脂率");
                            appendIfZero(messageBuilder, peopledata.getAjxl(), "安静心率");
                            appendIfZero(messageBuilder, peopledata.getWoli(), "握力");
                            appendIfZero(messageBuilder, peopledata.getLdty(), "立定跳远");
                            appendIfZero(messageBuilder, peopledata.getZwtqq(), "坐位体前屈");
                            appendIfZero(messageBuilder, peopledata.getSjlxt(), "双脚连续跳");
                            appendIfZero(messageBuilder, peopledata.getZphm(), "走平衡木");
                            appendIfZero(messageBuilder, peopledata.getSwmrzap(), "15米绕障碍跑");
                            appendSgzgIfZero(messageBuilder, peopledata.getSgzg(), peopledata.getSgzgval());
                            appendIfZero(messageBuilder, peopledata.getShengaotizhong(), "身高与体重");
                            appendIfZero(messageBuilder, peopledata.getShengaozuogao(), "身高与坐高");
                        } else if (tPeopleType.getId()==2) {
                            // 添加所有字段检查
                            appendIfZero(messageBuilder, peopledata.getShengao(), "身高");
                            appendIfZero(messageBuilder, peopledata.getTizhong(), "体重");
                            appendIfZero(messageBuilder, peopledata.getYaowei(), "腰围");
                            appendIfZero(messageBuilder, peopledata.getTunwei(), "臀围");
                            appendIfZero(messageBuilder, peopledata.getTzl(), "体脂率");
                            appendIfZero(messageBuilder, peopledata.getFhl(), "肺活量");
                            appendIfZero(messageBuilder, peopledata.getGlc(), "功率车");
                            appendIfZero(messageBuilder, peopledata.getWoli(), "握力");
                            appendIfZero(messageBuilder, peopledata.getZongtiao(), "纵跳");
                            appendFwcGwc(messageBuilder, peopledata.getFwc(), peopledata.getGwc());
                            appendIfZero(messageBuilder, peopledata.getYfzywqz(), "1分钟仰卧起坐");
                            appendIfZero(messageBuilder, peopledata.getZwtqq(), "坐位体前屈");
                            appendIfZero(messageBuilder, peopledata.getBydjzl(), "闭眼单脚站立");
                            appendIfZero(messageBuilder, peopledata.getXzfys(), "选择反应时");
                            appendIfZero(messageBuilder, peopledata.getBeili(), "背力");
                            appendIfZero(messageBuilder, peopledata.getHeartrate(), "安静脉搏");
                            appendIfZero(messageBuilder, peopledata.getSystolicpressure(), "收缩压");
                            appendIfZero(messageBuilder, peopledata.getDiastolicpressure(), "舒张压");

                            // 特殊字段
                            appendWithValue(messageBuilder, peopledata.getYaoweitunwei(), peopledata.getYaoweitunweival(), "腰臀比");
                            appendWithValue(messageBuilder, peopledata.getMaiyacha(), peopledata.getMaiyachaval(), "脉压差");

                            // 组合字段
                            appendIfZero(messageBuilder, peopledata.getShengaotizhong(), "身高与体重");
                            appendIfZero(messageBuilder, peopledata.getShengaofhl(), "身高与肺活量");
                            appendIfZero(messageBuilder, peopledata.getShengaowoli(), "身高与握力");
                            appendIfZero(messageBuilder, peopledata.getShengaobeili(), "身高与背力");
                            appendIfZero(messageBuilder, peopledata.getTizhongfhl(), "体重与肺活量");
                            appendIfZero(messageBuilder, peopledata.getTizhongwoli(), "体重与握力");
                            appendIfZero(messageBuilder, peopledata.getTizhongbeili(), "体重与背力");
                            appendIfZero(messageBuilder, peopledata.getYaoweishengaotizhong(), "腰围/身高与体重");
                            appendIfZero(messageBuilder, peopledata.getTunweishengaotizhong(), "臀围/身高与体重");

                            // 移除末尾顿号
//                                                                removeLastComma(builder);
                        } else if (tPeopleType.getId()==3) {
                            // 添加所有字段检查
                            appendIfZero(messageBuilder, peopledata.getShengao(), "身高");
                            appendIfZero(messageBuilder, peopledata.getTizhong(), "体重");
                            appendIfZeroSafe(messageBuilder, peopledata.getYaowei(), "腰围");
                            appendIfZeroSafe(messageBuilder, peopledata.getTunwei(), "臀围");
                            appendIfZero(messageBuilder, peopledata.getTzl(), "体脂率");
                            appendIfZero(messageBuilder, peopledata.getFhl(), "肺活量");
                            appendIfZero(messageBuilder, peopledata.getLfzydgtt(), "2分钟原地高抬腿");
                            appendIfZero(messageBuilder, peopledata.getWoli(), "握力");
                            appendIfZero(messageBuilder, peopledata.getZwtqq(), "坐位体前屈");
                            appendIfZero(messageBuilder, peopledata.getBydjzl(), "闭眼单脚站立");
                            appendIfZero(messageBuilder, peopledata.getXzfys(), "选择反应时");
                            appendIfZero(messageBuilder, peopledata.getSsmzz(), "30秒坐站");
                            appendIfZero(messageBuilder, peopledata.getHeartrate(), "安静脉搏");
                            appendIfZero(messageBuilder, peopledata.getSystolicpressure(), "收缩压");
                            appendIfZero(messageBuilder, peopledata.getDiastolicpressure(), "舒张压");

                            // 特殊字段
                            appendWithValue(messageBuilder, peopledata.getYaoweitunwei(), peopledata.getYaoweitunweival(), "腰臀比");
                            appendWithValue(messageBuilder, peopledata.getMaiyacha(), peopledata.getMaiyachaval(), "脉压差");

                            // 组合字段
                            appendIfZero(messageBuilder, peopledata.getShengaotizhong(), "身高与体重");
                            appendIfZero(messageBuilder, peopledata.getShengaofhl(), "身高与肺活量");
                            appendIfZero(messageBuilder, peopledata.getShengaowoli(), "身高与握力");
                            appendIfZero(messageBuilder, peopledata.getTizhongfhl(), "体重与肺活量");
                            appendIfZero(messageBuilder, peopledata.getTizhongwoli(), "体重与握力");
                            appendIfZeroSafe(messageBuilder, peopledata.getYaoweishengaotizhong(), "腰围/身高与体重");
                            appendIfZeroSafe(messageBuilder, peopledata.getTunweishengaotizhong(), "臀围/身高与体重");
                        }
                        removeLastComma(messageBuilder);
                        message = messageBuilder.toString();
                    }

                    if (!message.isEmpty()) {
                        //message不是空，说明有筛查不合格的指标，将这个人筛查不通过放入testWholeData的ispassscreening
                        testWholeData.setIspassscreening(0);
                        //筛查不通过指标名称，放入testWholeData的itemsispass
                        testWholeData.setItemsispass(message);
                        //返回前端筛查不通过指标名称
                        msg.append(testWholeData.getRealname()).append(message).append("筛查不通过。");
                    } else {
                        //message是空，说明没有筛查不合格的指标，将这个人筛查通过放入testWholeData的ispassscreening
                        testWholeData.setIspassscreening(1);
                    }
                }
            }
        }

        return testWholeData;
    }

    /**
     * 获取复测测试数据
     * @param testCorporeityResultsRetest
     * @return
     */
    public TestWholeDataRetest getTestWholeDataRetest(TestCorporeityResultsRetestDTO testCorporeityResultsRetest) {
        TestWholeDataRetest testWholeDataRetest = new TestWholeDataRetest();
        testWholeDataRetest.setSex(testCorporeityResultsRetest.getGender());
        testWholeDataRetest.setIdcard(testCorporeityResultsRetest.getIdNumber());
        testWholeDataRetest.setTowncountry(StringUtils.trimToEmpty(testCorporeityResultsRetest.getTownAndCountry()));
        testWholeDataRetest.setMechanismcode(StringUtils.trimToEmpty(testCorporeityResultsRetest.getInstitutionCode()));
        testWholeDataRetest.setInstrumentManufacturer(testCorporeityResultsRetest.getInstrumentManufacturer());
        testWholeDataRetest.setTestage(toSafeFloat(testCorporeityResultsRetest.getTestAge()));
        testWholeDataRetest.setTesttime(testCorporeityResultsRetest.getTestDate());
        testWholeDataRetest.setTestmonth(truncateToMonthWithoutZeroPadFast(testCorporeityResultsRetest.getTestDate()));
        testWholeDataRetest.setShengaoval(toSafeFloat(testCorporeityResultsRetest.getHeight()));
        testWholeDataRetest.setShengaoscore(toSafeFloat(testCorporeityResultsRetest.getHeightScore()));
        testWholeDataRetest.setShengaograde(StringUtils.trimToEmpty(testCorporeityResultsRetest.getHeightAssessment()));
        testWholeDataRetest.setShengaotime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfHeightTest()));
        testWholeDataRetest.setZuogaoval(toSafeFloat(testCorporeityResultsRetest.getSitUpHeight()));
        testWholeDataRetest.setZuogaoscore(toSafeFloat(testCorporeityResultsRetest.getSitUpHeightScore()));
        testWholeDataRetest.setZuogaograde(StringUtils.trimToEmpty(testCorporeityResultsRetest.getSitUpHeightAssessment()));
        testWholeDataRetest.setZuogaotime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfSitUpHeightTest()));
        testWholeDataRetest.setTizhongval(toSafeFloat(testCorporeityResultsRetest.getWeight()));
        testWholeDataRetest.setTizhongtime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfWeightTest()));
        testWholeDataRetest.setTzzsval(toSafeFloat(testCorporeityResultsRetest.getBodyMassIndex()));
        testWholeDataRetest.setTzzsscore(toSafeFloat(testCorporeityResultsRetest.getBmIScore()));
        testWholeDataRetest.setTzzsgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getBmiAssessment()));
        testWholeDataRetest.setTzzstime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfBMITest()));
        testWholeDataRetest.setTzlval(toSafeFloat(testCorporeityResultsRetest.getBodyFatRate()));
        testWholeDataRetest.setTzlscore(toSafeFloat(testCorporeityResultsRetest.getBodyFatRateScore()));
        testWholeDataRetest.setTzlgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getBodyFatRateAssessment()));
        testWholeDataRetest.setTzltime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfBodyFatRateTest()));
        testWholeDataRetest.setXiongweival(toSafeFloat(testCorporeityResultsRetest.getChestCircumference()));
        testWholeDataRetest.setXiongweiscore(toSafeFloat(testCorporeityResultsRetest.getChestCircumferenceScore()));
        testWholeDataRetest.setXiongweigrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getChestCircumferenceAssessment()));
        testWholeDataRetest.setXiongweitime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfChestCircumferenceTest()));
        testWholeDataRetest.setYaoweival(toSafeFloat(testCorporeityResultsRetest.getWaist()));
        testWholeDataRetest.setYaoweitime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfWaistTest()));
        testWholeDataRetest.setTunweival(toSafeFloat(testCorporeityResultsRetest.getHip()));
        testWholeDataRetest.setTunweitime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfHipTest()));
        testWholeDataRetest.setFhlval(toSafeFloat(testCorporeityResultsRetest.getVitalCapacity()));
        testWholeDataRetest.setFhlscore(toSafeFloat(testCorporeityResultsRetest.getVitalCapacityScore()));
        testWholeDataRetest.setFhlgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getVitalCapacityAssessment()));
        testWholeDataRetest.setFhltime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfVitalCapacityTest()));
        testWholeDataRetest.setGlcval(toSafeFloat(testCorporeityResultsRetest.getRelativeValuesOfTheSecondLevelLoadTestOnAPowerBike()));
        testWholeDataRetest.setGlcscore(toSafeFloat(testCorporeityResultsRetest.getSecondLevelLoadTestOnAPowerBikeScore()));
        testWholeDataRetest.setGlcgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getSecondLevelLoadTestOnAPowerBikeAssessment()));
        testWholeDataRetest.setGlctime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfSecondLevelLoadTestOnAPowerBike()));
        testWholeDataRetest.setLfzydgttval(toSafeFloat(testCorporeityResultsRetest.getMinute2LegRaisesInPlace()));
        testWholeDataRetest.setLfzydgttscore(toSafeFloat(testCorporeityResultsRetest.getMinute2LegRaisesInPlaceScore()));
        testWholeDataRetest.setLfzydgttgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getMinute2LegRaisesInPlaceAssessment()));
        testWholeDataRetest.setLfzydgtttime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getEndOfMinute2LegRaisesInPlaceTest()));
        testWholeDataRetest.setLfzydgttzval(toSafeFloat(testCorporeityResultsRetest.getMinute2LegRaisesInPlaceLeftLeg()));
        testWholeDataRetest.setLfzydgttztime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfMinute2LegRaisesInPlaceLeftLeg()));
        testWholeDataRetest.setLfzydgttyval(toSafeFloat(testCorporeityResultsRetest.getMinute2LegRaisesInPlaceRightLeg()));
        testWholeDataRetest.setLfzydgttytime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfMinute2LegRaisesInPlaceRightLegTest()));
        testWholeDataRetest.setAjxlval(toSafeFloat(testCorporeityResultsRetest.getRestingHeartRate()));
        testWholeDataRetest.setAjxltime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfRestingHeartRate()));
        testWholeDataRetest.setWolival(toSafeFloat(testCorporeityResultsRetest.getGripStrength()));
        testWholeDataRetest.setWoliscore(toSafeFloat(testCorporeityResultsRetest.getGripStrengthScore()));
        testWholeDataRetest.setWoligrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getGripStrengthAssessment()));
        testWholeDataRetest.setWolitime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfGripStrengthTest()));
        testWholeDataRetest.setZongtiaoval(toSafeFloat(testCorporeityResultsRetest.getVerticalJump()));
        testWholeDataRetest.setZongtiaoscore(toSafeFloat(testCorporeityResultsRetest.getVerticalJumpScore()));
        testWholeDataRetest.setZongtiaograde(StringUtils.trimToEmpty(testCorporeityResultsRetest.getVerticalJumpAssessment()));
        testWholeDataRetest.setZongtiaotime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfVerticalJumpTest()));
        testWholeDataRetest.setFwcval(toSafeFloat(testCorporeityResultsRetest.getPushUp()));
        testWholeDataRetest.setFwcscore(toSafeFloat(testCorporeityResultsRetest.getPushUpScore()));
        testWholeDataRetest.setFwcgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getPushUpAssessment()));
        testWholeDataRetest.setFwctime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfPushUpTest()));
        testWholeDataRetest.setGwcval(toSafeFloat(testCorporeityResultsRetest.getKneelingPushUp()));
        testWholeDataRetest.setGwcscore(toSafeFloat(testCorporeityResultsRetest.getKneelingPushUpScore()));
        testWholeDataRetest.setGwcgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getKneelingPushUpAssessment()));
        testWholeDataRetest.setGwctime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfKneelingPushUpTest()));
        testWholeDataRetest.setYfzywqzval(toSafeFloat(testCorporeityResultsRetest.getMinute1SitUps()));
        testWholeDataRetest.setYfzywqzscore(toSafeFloat(testCorporeityResultsRetest.getMinute1SitUpsScore()));
        testWholeDataRetest.setYfzywqzgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getMinute1SitUpsAssessment()));
        testWholeDataRetest.setYfzywqztime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfMinute1SitUpsTest()));
        testWholeDataRetest.setZwtqqval(toSafeFloat(testCorporeityResultsRetest.getSeatedForwardBending()));
        testWholeDataRetest.setZwtqqscore(toSafeFloat(testCorporeityResultsRetest.getSeatedForwardBendingScore()));
        testWholeDataRetest.setZwtqqgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getSeatedForwardBendingAssessment()));
        testWholeDataRetest.setZwtqqtime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfSeatedForwardBendingTest()));
        testWholeDataRetest.setBydjzlval(toSafeFloat(testCorporeityResultsRetest.getEyesClosedOneLeggedStand()));
        testWholeDataRetest.setBydjzlscore(toSafeFloat(testCorporeityResultsRetest.getEyesClosedOneLeggedStandScore()));
        testWholeDataRetest.setBydjzlgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getEyesClosedOneLeggedStandAssessment()));
        testWholeDataRetest.setBydjzltime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfEyesClosedOnLeggedStandTest()));
        testWholeDataRetest.setXzfysval(toSafeFloat(testCorporeityResultsRetest.getSelectionReactionTime()));
        testWholeDataRetest.setXzfysscore(toSafeFloat(testCorporeityResultsRetest.getSelectionReactionTimeScore()));
        testWholeDataRetest.setXzfysgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getSelectionReactionTimeAssessment()));
        testWholeDataRetest.setXzfystime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfSelectionReactionTimeTest()));
        testWholeDataRetest.setBeilival(toSafeFloat(testCorporeityResultsRetest.getBackStrength()));
        testWholeDataRetest.setBeilitime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfBackStrengthTest()));
        testWholeDataRetest.setSsmzzval(toSafeFloat(testCorporeityResultsRetest.getSeconds30SittingAndStanding()));
        testWholeDataRetest.setSsmzzscore(toSafeFloat(testCorporeityResultsRetest.getSeconds30SittingAndStandingScore()));
        testWholeDataRetest.setSsmzzgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getSeconds30SittingAndStandingAssessment()));
        testWholeDataRetest.setSsmzztime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfSeconds30SittingAndStandingTest()));
        testWholeDataRetest.setLdtyval(toSafeFloat(testCorporeityResultsRetest.getStandingLongJump()));
        testWholeDataRetest.setLdtyscore(toSafeFloat(testCorporeityResultsRetest.getStandingLongJumpScore()));
        testWholeDataRetest.setLdtygrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getStandingLongJumpAssessment()));
        testWholeDataRetest.setLdtytime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfStandingLongJumpTest()));
        testWholeDataRetest.setSjlxtval(toSafeFloat(testCorporeityResultsRetest.getContinuousJumpsOnBothFeet()));
        testWholeDataRetest.setSjlxtscore(toSafeFloat(testCorporeityResultsRetest.getContinuousJumpsOnBothFeetScore()));
        testWholeDataRetest.setSjlxtgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getContinuousJumpsOnBothFeetAssessment()));
        testWholeDataRetest.setSjlxttime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfContinuousJumpsOnBothFeetTest()));
        testWholeDataRetest.setSwmrzapval(toSafeFloat(testCorporeityResultsRetest.getMeter15RunAroundObstacles()));
        testWholeDataRetest.setSwmrzapscore(toSafeFloat(testCorporeityResultsRetest.getMeter15RunAroundObstaclesScore()));
        testWholeDataRetest.setSwmrzapgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getMeter15RunAroundObstaclesAssessment()));
        testWholeDataRetest.setSwmrzaptime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfMeter15RunAroundObstaclesTest()));
        testWholeDataRetest.setZphmval(toSafeFloat(testCorporeityResultsRetest.getWalkingOnABalanceBeam()));
        testWholeDataRetest.setZphmscore(toSafeFloat(testCorporeityResultsRetest.getWalkingSidewaysOnABalanceBeamScore()));
        testWholeDataRetest.setZphmgrade(StringUtils.trimToEmpty(testCorporeityResultsRetest.getWalkingSidewaysOnABalanceBeamAssessment()));
        testWholeDataRetest.setZphmtime(StringUtils.trimToEmpty(testCorporeityResultsRetest.getDateOfWalkingSidewaysOnABalanceBeamTest()));
        testWholeDataRetest.setZphmnb(StringUtils.trimToEmpty(testCorporeityResultsRetest.getWalkingSidewaysOnABalanceBeam()));
        if (testCorporeityResultsRetest.getNationalPhysicalFitnessCompositeScore() != null) {
            //综合得分不为空，表明参与评价的指标测试完成
            testWholeDataRetest.setZonghescore(toSafeFloat(testCorporeityResultsRetest.getNationalPhysicalFitnessCompositeScore()));
            testWholeDataRetest.setZonghegrade(testCorporeityResultsRetest.getNationalPhysicalFitnessCompositeAssessment());
        }
        testWholeDataRetest.setGps(StringUtils.trimToEmpty(testCorporeityResultsRetest.getGps()));
        //是否复测通过;默认复测通过，后期根据需要调整
        testWholeDataRetest.setIspassretest(1);
        //是否国测
        testWholeDataRetest.setType(1);
        return testWholeDataRetest;
    }

    /**
     * 获取token
     * @param reqInfo
     * @return
     */
    @Override
    public Object generateToken(GenerateTokenReqDTO reqInfo) {
//        System.out.println("appkey:"+reqInfo.getAppKey()+"---timestamp:" + reqInfo.getTimestamp() + "---nonce:" + reqInfo.getNonce() + "---sign:" + reqInfo.getSign());
        Map<String, Object> messageMap = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();

        // 验证参数
        boolean isValid = signatureVerificationService.verifySignatureEnhanced(reqInfo.getSign(), reqInfo.getTimestamp(), reqInfo.getNonce(), reqInfo.getAppKey());
//                SignUtils.verifyParams(reqInfo.getAppKey(), reqInfo.getTimestamp(), reqInfo.getNonce(), reqInfo.getSign());

        if (isValid) {
            // 验证签名
            SysUserLoginDTO userMap = getAppSecret(reqInfo.getAppKey());
            if (null == userMap) {
                messageMap.put("code", 400);
                messageMap.put("message", "参数不正确,请重新填写参数");
                return messageMap;
            }
            // 验证用户状态
            if (userMap.getStatus().equals("1")) {
                messageMap.put("code", 400);
                messageMap.put("message", "用户已停用");
                return messageMap;
            }
            // 验证该监测点是否已经上报
//            System.out.println("deptId:"+userMap.getDeptId());
            int exists = uploadMapper.existsTestPoint(userMap.getDeptId());
            if (exists == 0) {
                messageMap.put("code", 400);
                messageMap.put("message", "该监测点本年度未上报");
                return messageMap;
            }

            System.out.println("签名通过");
            // 5. 重放攻击检查（使用 Redis 替代 Ehcache）
            boolean isReplayAttack = isReplayAttackUsingRedis(reqInfo.getAppKey(), reqInfo.getTimestamp(), reqInfo.getNonce(), reqInfo.getSign());
            if (!isReplayAttack) {
                messageMap.put("code", 400);
                messageMap.put("message", "请勿重复请求");
                return messageMap;
            }

            // 6. 获取或生成 token
            String token = getOrGenerateToken(reqInfo.getAppKey());
            if (token == null) {
                messageMap.put("code", 500);
                messageMap.put("message", "生成 token 失败");
                return messageMap;
            }

            // 7. 返回成功响应
            messageMap.put("code", 200);
            dataMap.put("organizationcode", userMap.getOrganizationcode());
            dataMap.put("orgName", userMap.getDeptName());
            dataMap.put("token", token);
            dataMap.put("expires_in", 3600);
            messageMap.put("data", dataMap);

            return messageMap;
        }
        messageMap.put("code", 400);
        messageMap.put("message", "参数不正确");
        return messageMap;
    }

    /**
     * 获取appKey对应的user
     *
     * @return
     */
    public SysUserLoginDTO getAppSecret(String appKey) {
//        SysUserLogin user = new SysUserLogin();
//        user.setLoginName(appKey);
        //对数据库中密码解密
        return sysUserInfoMapper.getByLg(appKey);
    }

    public boolean matches(SysUserLoginDTO user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    /**
     * 使用 Redis 实现重放攻击检查
     */
    private boolean isReplayAttackUsingRedis(String appKey, Long timestamp, Long nonce, String sign) {
        // 生成唯一标识（使用 nonce）
        String replayKey = "replay:" + appKey + ":" + nonce;

        // 检查是否已存在
        if (redisService.hasKey(replayKey)) {
            return false; // 已存在，视为重放攻击
        }

        // 存储并设置过期时间（5分钟）
        redisService.setCacheObject(replayKey, "1", 5L, TimeUnit.MINUTES);
        return true;
    }

    /**
     * 获取或生成 token
     */
    private String getOrGenerateToken(String appKey) {
        String tokenKey = "token:" + Constant.APP_KEY + ":" + appKey;

        // 尝试从 Redis 获取 token
        String token = (String) redisService.getCacheObject(tokenKey);

        // 检查 token 有效性
        if (token != null) {
            R validationResult = JwtHelper.checkToken(token);
            if (validationResult.getCode() == 200) { // 假设 200 表示成功
                return token;
            } else {
                // 删除无效 token
                redisService.deleteObject(tokenKey);
            }
        }

        // 生成新 token
        try {
            token = JwtHelper.createToken(appKey, 1000 * 60 * 60);
            // 存储到 Redis（有效期 1 小时）
            redisService.setCacheObject(tokenKey, token, 3600L, TimeUnit.SECONDS);
            return token;
        } catch (Exception e) {
            System.err.println("生成 token 失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取登录用户
     * @param request
     * @return
     */
    public String getLoginUser(HttpServletRequest request){
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
//        System.out.println("-----------------------------" + token);
        if (StringUtils.isEmpty(token)) return null;

        try
        {
            if (StringUtils.isNotEmpty(token))
            {
                String userkey = JwtHelper.parseAppKeyFromToken(token);
                return userkey;
            }
        }
        catch (Exception e)
        {
//            System.out.println("+-+++---++-+-+-"+e.getMessage());
        }
        return "";

    }
    /**
     * 处理国民体质数据，返回整个有效列表
     */
    private <T> List<T> processTestDataList(String isCheckRetest,
                                            List<Map<String, Object>> outerList,
                                            String innerKey,
                                            Class<T> dtoClass) {
        List<T> resultList = new ArrayList<>();
        if (outerList == null || outerList.isEmpty()) {
            return resultList;
        }

        // 遍历外层列表
        for (Map<String, Object> outerMap : outerList) {
            // 获取外层GPS
            Object outerGPS = outerMap.get("gps");

            // 获取内层数据列表
            Object innerData = outerMap.get(innerKey);
            if (!(innerData instanceof List)) continue;

            List<?> innerList = (List<?>) innerData;

            // 遍历内层列表
            for (Object item : innerList) {
                if (!(item instanceof Map)) continue;

                @SuppressWarnings("unchecked")
                Map<String, Object> innerMap = (Map<String, Object>) item;

                // 检查GPS有效性（如果需要）
                if ("1".equals(isCheckRetest)) {
                    if (!isValidGPS(outerGPS, innerMap)) {
                        continue; // 无效GPS跳过
                    }
                }

                // 转换为DTO对象
                T dto = convertMapToDto(innerMap, dtoClass);
                if (dto == null) continue;

                resultList.add(dto);
            }
        }

        return resultList;
    }
    /**
     * 检查GPS有效性（与之前相同）
     */
    private boolean isValidGPS(Object outerGPS, Map<String, Object> innerMap) {
        // 1. 优先使用外层GPS
        if (outerGPS != null) {
            String gpsStr = outerGPS.toString().trim();
            if (!gpsStr.isEmpty() && !"null".equalsIgnoreCase(gpsStr) && !"999.99,999.99".equals(gpsStr)) {
                return true;
            }
        }

        // 2. 其次使用内层GPS
        Object innerGPS = innerMap.get("gps");
        if (innerGPS != null) {
            String gpsStr = innerGPS.toString().trim();
            if (!gpsStr.isEmpty() && !"null".equalsIgnoreCase(gpsStr) && !"999.99,999.99".equals(gpsStr)) {
                return true;
            }
        }

        // 3. 都没有有效GPS
        return false;
    }
    /**
     * 处理单表数据，只取最新的一条有效记录
     */
    private <T> T processSingleTestData(String isCheckRetest,
                                        List<Map<String, Object>> outerList,
                                        String innerKey,
                                        Class<T> dtoClass) {
        if (outerList == null || outerList.isEmpty()) {
            return null;
        }

        T latestDto = null;
        String latestSpecificTime = null;

        for (Map<String, Object> outerMap : outerList) {
            // 获取外层GPS
            Object outerGPS = outerMap.get("gps");

            // 获取内层数据
            Object innerData = outerMap.get(innerKey);
            if (!(innerData instanceof List)) continue;

            for (Object item : (List<?>) innerData) {
                if (!(item instanceof Map)) continue;

                @SuppressWarnings("unchecked")
                Map<String, Object> innerMap = (Map<String, Object>) item;

                // 验证GPS（如果需要）
                if ("1".equals(isCheckRetest)) {
                    String gps = getValidGPS(outerGPS, innerMap);
                    if (gps == null || "999.99,999.99".equals(gps)) {
                        continue; // 无效GPS跳过
                    }
                }

                // 转换为DTO
                T dto = convertMapToDto(innerMap, dtoClass);
                if (dto == null) continue;

                // 获取特定时间（用于判断最新记录）
                String specificTime = getSpecificTime(dto);

                // 选择最新记录
                if (latestDto == null) {
                    latestDto = dto;
                    latestSpecificTime = specificTime;
                } else if (specificTime != null &&
                        (latestSpecificTime == null ||
                                specificTime.compareTo(latestSpecificTime) > 0)) {
                    latestDto = dto;
                    latestSpecificTime = specificTime;
                }
            }
        }

        return latestDto;
    }

    /**
     * 获取特定时间（根据不同类型）
     */
    private String getSpecificTime(Object dto) {
        if (dto instanceof TestTurgoscopeDTO) {
            return ((TestTurgoscopeDTO) dto).getSpecifictime();
        } else if (dto instanceof TestBodyfatDTO) {
            return ((TestBodyfatDTO) dto).getSpecificTime();
        } else if (dto instanceof TestPowerDTO) {
            return ((TestPowerDTO) dto).getSpecifictime();
        } else if (dto instanceof TestPowerHeartrateDTO) {
            return ((TestPowerHeartrateDTO) dto).getSpecifictime();
        } else if (dto instanceof TestCorporeityDTO) {
            // 国民体质数据可能需要特殊处理
            return ((TestCorporeityDTO) dto).getTestTime(); // 根据实际字段调整
        }
        return null;
    }

    /**
     * 获取有效GPS（优先使用外层GPS）
     */
    private String getValidGPS(Object outerGPS, Map<String, Object> innerMap) {
        // 优先使用外层GPS
        if (outerGPS != null) {
            String gpsStr = outerGPS.toString().trim();
            if (!gpsStr.isEmpty() && !"null".equalsIgnoreCase(gpsStr)) {
                return gpsStr;
            }
        }

        // 其次使用内层GPS
        Object innerGPS = innerMap.get("gps");
        if (innerGPS != null) {
            String gpsStr = innerGPS.toString().trim();
            if (!gpsStr.isEmpty() && !"null".equalsIgnoreCase(gpsStr)) {
                return gpsStr;
            }
        }

        return null;
    }

    /**
     * Map转DTO
     */
    private <T> T convertMapToDto(Map<String, Object> map, Class<T> clazz) {
        try {
            String jsonString = JSON.toJSONString(map);
            return JSON.parseObject(jsonString, clazz);
        } catch (Exception e) {
            return null;
        }
    }
    private void setmembers(TestWholeData testWholeData, TestMemberDTO member){
        // 设置基本个人信息
        testWholeData.setRealname(member.getName());
        testWholeData.setSex(member.getSex());
        testWholeData.setBirthdate(member.getBirthdate());
        testWholeData.setAge(toSafeFloat(member.getAge()));

        // 设置民族、地址、工作单位等文本信息
        testWholeData.setNation(StringUtils.trimToEmpty(member.getNation()));
        testWholeData.setAddress(StringUtils.trimToEmpty(member.getAddress()));
        testWholeData.setWorkunit(StringUtils.trimToEmpty(member.getWorkunit()));

        // 设置时间戳和状态信息
        testWholeData.setCreatetime(StringUtils.trimToEmpty(member.getCreatetime()));
        testWholeData.setUpdatetime(StringUtils.trimToEmpty(member.getUpdatetime()));
        testWholeData.setDeleted(StringUtils.trimToEmpty(member.getDeleted()));

        // 设置职业相关信息
        testWholeData.setPosition(StringUtils.trimToEmpty(member.getPosition()));
        testWholeData.setOccupation(StringUtils.trimToEmpty(member.getOccupation()));
        testWholeData.setIndustry(StringUtils.trimToEmpty(member.getIndustry()));
        testWholeData.setTowncountry(StringUtils.trimToEmpty(member.getTownAndCountry()));
        testWholeData.setCulture(StringUtils.trimToEmpty(member.getCulture()));

        // 设置联系方式和机构信息
        testWholeData.setPhone(StringUtils.trimToEmpty(member.getPhone()));
        testWholeData.setMechanismname(StringUtils.trimToEmpty(member.getMechanismname()));
        testWholeData.setMechanismcode(StringUtils.trimToEmpty(member.getMechanismcode()));
    }
    private Double getFirstValidTestAge(List<TestCorporeityDTO> corporeitys,
                                        TestTurgoscopeDTO turgoscope,
                                        TestBodyfatDTO bodyfat,
                                        TestPowerDTO power,
                                        TestPowerHeartrateDTO powerHeartrate) {
        // 检查单个对象（按优先级排序）
        if (bodyfat != null && bodyfat.getTestAge() != null) {
            return bodyfat.getTestAge();
        }
        if (power != null && power.getTestage() != null) {
            return power.getTestage();
        }
        if (turgoscope != null && turgoscope.getTestage() != null) {
            return turgoscope.getTestage();
        }
        if (powerHeartrate != null && powerHeartrate.getTestage() != null) {
            return powerHeartrate.getTestage();
        }

        // 检查列表
        if (corporeitys != null) {
            for (TestCorporeityDTO corp : corporeitys) {
                if (corp != null) {
                    Double age = corp.getTestAge();
                    if (age != null) {
                        return age;
                    }
                }
            }
        }

        return null; // 所有来源都无效
    }

    /**
     * 处理Corporeity数据，将数据映射到TestWholeData对象中
     *
     * @param testWholeData 整个测试数据对象
     * @param corporeitys   测试数据列表
     * @return 处理后的GPS信息
     */
    private String processCorporeitys(TestWholeData testWholeData, List<TestCorporeityDTO> corporeitys) {
        // 定义处理映射表
        Map<Integer, ReceptDataServiceImpl.QuadConsumer<TestWholeData, TestCorporeityDTO>> handlers = new HashMap<>();
        // 初始化为默认GPS值
        String finalGps = "0.000,0.000";

        // 1. 定义所有处理逻辑（使用辅助方法）
        handlers.put(1, (twd, corp) -> {
            twd.setShengaoval(toSafeFloat(corp.getTestValue()));
            twd.setShengaoscore(toSafeFloat(corp.getScore()));
            twd.setShengaograde(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setShengaotime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setShengaogps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(3, (twd, corp) -> {
            twd.setZuogaoval(toSafeFloat(corp.getTestValue()));
            twd.setZuogaoscore(toSafeFloat(corp.getScore()));
            twd.setZuogaograde(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setZuogaotime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setZuogaogps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(2, (twd, corp) -> {
            twd.setTizhongval(toSafeFloat(corp.getTestValue()));
            twd.setTizhongtime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setTizhonggps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(4, (twd, corp) -> {
            twd.setTzzsval(toSafeFloat(corp.getTestValue()));
            twd.setTzzsscore(toSafeFloat(corp.getScore()));
            twd.setTzzsgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setTzzstime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setTzzsgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(8, (twd, corp) -> {
            twd.setTzlval(toSafeFloat(corp.getTestValue()));
            twd.setTzlscore(toSafeFloat(corp.getScore()));
            twd.setTzlgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setTzltime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setTzlgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(5, (twd, corp) -> {
            twd.setXiongweival(toSafeFloat(corp.getTestValue()));
            twd.setXiongweitime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setXiongweigps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(6, (twd, corp) -> {
            twd.setYaoweival(toSafeFloat(corp.getTestValue()));
            twd.setYaoweitime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setYaoweigps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(7, (twd, corp) -> {
            twd.setTunweival(toSafeFloat(corp.getTestValue()));
            twd.setTunweiscore(toSafeFloat(corp.getScore()));
            twd.setTunweigrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setTunweitime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setTunweigps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(9, (twd, corp) -> {
            twd.setFhlval(toSafeFloat(corp.getTestValue()));
            twd.setFhlscore(toSafeFloat(corp.getScore()));
            twd.setFhlgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setFhltime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setFhlgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(10, (twd, corp) -> {
            twd.setGlcval(toSafeFloat(corp.getTestValue()));
            twd.setGlcscore(toSafeFloat(corp.getScore()));
            twd.setGlcgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setGlctime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setGlcgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(11, (twd, corp) -> {
            twd.setLfzydgttval(toSafeFloat(corp.getTestValue()));
            twd.setLfzydgttscore(toSafeFloat(corp.getScore()));
            twd.setLfzydgttgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setLfzydgtttime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setLfzydgttgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(31, (twd, corp) -> {
            twd.setLfzydgttzval(toSafeFloat(corp.getTestValue()));
            twd.setLfzydgttztime(StringUtils.trimToEmpty(corp.getSpecificTime()));
        });

        handlers.put(32, (twd, corp) -> {
            twd.setLfzydgttyval(toSafeFloat(corp.getTestValue()));
            twd.setLfzydgttytime(StringUtils.trimToEmpty(corp.getSpecificTime()));
        });

        handlers.put(12, (twd, corp) -> {
            twd.setAjxlval(toSafeFloat(corp.getTestValue()));
            twd.setAjxlscore(toSafeFloat(corp.getScore()));
            twd.setAjxlgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setAjxltime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setAjxlgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(13, (twd, corp) -> {
            twd.setWolival(toSafeFloat(corp.getTestValue()));
            twd.setWoliscore(toSafeFloat(corp.getScore()));
            twd.setWoligrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setWolitime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setWoligps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(14, (twd, corp) -> {
            twd.setZongtiaoval(toSafeFloat(corp.getTestValue()));
            twd.setZongtiaoscore(toSafeFloat(corp.getScore()));
            twd.setZongtiaograde(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setZongtiaotime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setZongtiaogps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(15, (twd, corp) -> {
            twd.setFwcval(toSafeFloat(corp.getTestValue()));
            twd.setFwcscore(toSafeFloat(corp.getScore()));
            twd.setFwcgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setFwctime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setFwcgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(16, (twd, corp) -> {
            twd.setGwcval(toSafeFloat(corp.getTestValue()));
            twd.setGwcscore(toSafeFloat(corp.getScore()));
            twd.setGwcgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setGwctime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setGwcgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(17, (twd, corp) -> {
            twd.setYfzywqzval(toSafeFloat(corp.getTestValue()));
            twd.setYfzywqzscore(toSafeFloat(corp.getScore()));
            twd.setYfzywqzgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setYfzywqztime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setYfzywqzgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(18, (twd, corp) -> {
            twd.setZwtqqval(toSafeFloat(corp.getTestValue()));
            twd.setZwtqqscore(toSafeFloat(corp.getScore()));
            twd.setZwtqqgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setZwtqqtime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setZwtqqgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(19, (twd, corp) -> {
            twd.setBydjzlval(toSafeFloat(corp.getTestValue()));
            twd.setBydjzlscore(toSafeFloat(corp.getScore()));
            twd.setBydjzlgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setBydjzltime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setBydjzlgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(20, (twd, corp) -> {
            twd.setXzfysval(toSafeFloat(corp.getTestValue()));
            twd.setXzfysscore(toSafeFloat(corp.getScore()));
            twd.setXzfysgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setXzfystime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setXzfysgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(21, (twd, corp) -> {
            twd.setBeilival(toSafeFloat(corp.getTestValue()));
            twd.setBeiliscore(toSafeFloat(corp.getScore()));
            twd.setBeiligrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setBeilitime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setBeiligps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(22, (twd, corp) -> {
            twd.setSsmzzval(toSafeFloat(corp.getTestValue()));
            twd.setSsmzzscore(toSafeFloat(corp.getScore()));
            twd.setSsmzzgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setSsmzztime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setSsmzzgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(23, (twd, corp) -> {
            twd.setLdtyval(toSafeFloat(corp.getTestValue()));
            twd.setLdtyscore(toSafeFloat(corp.getScore()));
            twd.setLdtygrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setLdtytime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setLdtygps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(24, (twd, corp) -> {
            twd.setSjlxtval(toSafeFloat(corp.getTestValue()));
            twd.setSjlxtscore(toSafeFloat(corp.getScore()));
            twd.setSjlxtgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setSjlxttime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setSjlxtgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(25, (twd, corp) -> {
            twd.setSwmrzapval(toSafeFloat(corp.getTestValue()));
            twd.setSwmrzapscore(toSafeFloat(corp.getScore()));
            twd.setSwmrzapgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setSwmrzaptime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setSwmrzapgps(StringUtils.trimToEmpty(corp.getGps()));
        });

        handlers.put(26, (twd, corp) -> {
            twd.setZphmval(toSafeFloat(corp.getTestValue()));
            twd.setZphmscore(toSafeFloat(corp.getScore()));
            twd.setZphmgrade(StringUtils.trimToEmpty(corp.getGrade()));
            twd.setZphmtime(StringUtils.trimToEmpty(corp.getSpecificTime()));
            twd.setZphmgps(StringUtils.trimToEmpty(corp.getGps()));
            twd.setZphmnb(corp.getValueOne() == null ? "" : corp.getValueOne().toString());
        });

        handlers.put(100, (twd, corp) -> {
            // 安全处理空值
            String scoreStr = corp.getScore() == null ? "" : corp.getScore().toString();
            if (StringUtils.isEmpty(scoreStr)) {
                // 该会员没有综合得分，表明该会员参与评价的指标未测试完，测试状态是未完成
                twd.setStatus(0);
            } else {
                // 综合得分不为空，表明参与评价的指标测试完成
                twd.setZonghescore(toSafeFloat(corp.getScore()));
                twd.setZonghegrade(corp.getGrade());
            }
        });

        // 2. 创建已处理标记集
        Set<Integer> processedCodes = new HashSet<>();

        // 3. 单次遍历处理所有逻辑
        for (TestCorporeityDTO corp : corporeitys) {
            int itemCode = corp.getItemCode();

            // 只处理每个itemCode的第一个匹配项
            if (handlers.containsKey(itemCode) && !processedCodes.contains(itemCode)) {
                // 执行主处理逻辑
                handlers.get(itemCode).accept(testWholeData, corp);

                // 4. 更新GPS（除特殊itemCode外）
                if (itemCode != 31 && itemCode != 32 && itemCode != 100) {
                    if (finalGps.equals("0.000,0.000") &&
                            StringUtils.isNotEmpty(corp.getGps())) {
                        finalGps = corp.getGps();
                    }
                }

                // 标记为已处理
                processedCodes.add(itemCode);

                // 所有处理完成时提前退出
                if (processedCodes.size() == handlers.size()) {
                    break;
                }
            }
        }

        // 5. 返回最终确定的GPS值
        return finalGps;
    }
    // 四参数消费者接口定义
    @FunctionalInterface
    interface QuadConsumer<A, B> {
        void accept(A a, B b);
    }
    /**
     *
     * @param testWholeData
     * @param bodyfat
     */
    private void setbodyfat(TestWholeData testWholeData, TestBodyfatDTO bodyfat){
        testWholeData.setShengao(bodyfat.getSHENGAO() == null ? "" : bodyfat.getSHENGAO().toString());
        testWholeData.setTizhong(bodyfat.getTIZHONG() == null ? "" : bodyfat.getTIZHONG().toString());
        testWholeData.setK1Zongzukang(bodyfat.getK1_ZONGZUKANG() == null ? "" : bodyfat.getK1_ZONGZUKANG().toString());
        testWholeData.setK5Zongzukang(bodyfat.getK5_ZONGZUKANG() == null ? "" : bodyfat.getK5_ZONGZUKANG().toString());
        testWholeData.setK20Zongzukang(bodyfat.getK20_ZONGZUKANG() == null ? "" : bodyfat.getK20_ZONGZUKANG().toString());
        testWholeData.setK50Zongzukang(bodyfat.getK50_ZONGZUKANG() == null ? "" : bodyfat.getK50_ZONGZUKANG().toString());
        testWholeData.setK50Xiangweicha(bodyfat.getK50_XIANGWEICHA() == null ? "" : bodyfat.getK50_XIANGWEICHA().toString());
        testWholeData.setK50Zuoshangzhizukang(bodyfat.getK50_ZUOSHANGZHIZUKANG() == null ? "" : bodyfat.getK50_ZUOSHANGZHIZUKANG().toString());
        testWholeData.setK50Youshangzhizukang(bodyfat.getK50_YOUSHANGZHIZUKANG() == null ? "" : bodyfat.getK50_YOUSHANGZHIZUKANG().toString());
        testWholeData.setK50Quganzukang(bodyfat.getK50_QUGANZUKANG() == null ? "" : bodyfat.getK50_QUGANZUKANG().toString());
        testWholeData.setK50Zuoxiazhizukang(bodyfat.getK50_ZUOXIAZHIZUKANG() == null ? "" : bodyfat.getK50_ZUOXIAZHIZUKANG().toString());
        testWholeData.setK50Youxiazhizukang(bodyfat.getK50_YOUXIAZHIZUKANG() == null ? "" : bodyfat.getK50_YOUXIAZHIZUKANG().toString());
        testWholeData.setK100Zongzukang(bodyfat.getK100_ZONGZUKANG() == null ? "" : bodyfat.getK100_ZONGZUKANG().toString());
        testWholeData.setK250Zongzukang(bodyfat.getK250_ZONGZUKANG() == null ? "" : bodyfat.getK250_ZONGZUKANG().toString());
        testWholeData.setK500Zongzukang(bodyfat.getK500_ZONGZUKANG() == null ? "" : bodyfat.getK500_ZONGZUKANG().toString());
        testWholeData.setK1000Zongzukang(bodyfat.getK1000_ZONGZUKANG() == null ? "" : bodyfat.getK1000_ZONGZUKANG().toString());
        testWholeData.setBztzBiaozhunzhi(bodyfat.getBZTZ_BIAOZHUNZHI() == null ? "" : bodyfat.getBZTZ_BIAOZHUNZHI().toString());
        testWholeData.setBztzXiajie(bodyfat.getBZTZ_XIAJIE() == null ? "" : bodyfat.getBZTZ_XIAJIE().toString());
        testWholeData.setBztzShangjie(bodyfat.getBZTZ_SHANGJIE() == null ? "" : bodyfat.getBZTZ_SHANGJIE().toString());
        testWholeData.setQztzShicezhi(bodyfat.getQZTZ_SHICEZHI() == null ? "" : bodyfat.getQZTZ_SHICEZHI().toString());
        testWholeData.setQztzXiajie(bodyfat.getQZTZ_XIAJIE() == null ? "" : bodyfat.getQZTZ_XIAJIE().toString());
        testWholeData.setQztzShangjie(bodyfat.getQZTZ_SHANGJIE() == null ? "" : bodyfat.getQZTZ_SHANGJIE().toString());
        testWholeData.setTzflShicezhi(bodyfat.getTZFL_SHICEZHI() == null ? "" : bodyfat.getTZFL_SHICEZHI().toString());
        testWholeData.setTzflXiajie(bodyfat.getTZFL_XIAJIE() == null ? "" : bodyfat.getTZFL_XIAJIE().toString());
        testWholeData.setTzflShangjie(bodyfat.getTZFL_SHANGJIE() == null ? "" : bodyfat.getTZFL_SHANGJIE().toString());
        testWholeData.setStjrlShicezhi(bodyfat.getSTJRL_SHICEZHI() == null ? "" : bodyfat.getSTJRL_SHICEZHI().toString());
        testWholeData.setStjrlXiajie(bodyfat.getSTJRL_XIAJIE() == null ? "" : bodyfat.getSTJRL_XIAJIE().toString());
        testWholeData.setStjrlShangjie(bodyfat.getSTJRL_SHANGJIE() == null ? "" : bodyfat.getSTJRL_SHANGJIE().toString());
        testWholeData.setGgjrShicezhi(bodyfat.getGGJR_SHICEZHI() == null ? "" : bodyfat.getGGJR_SHICEZHI().toString());
        testWholeData.setGgjrXiajie(bodyfat.getGGJR_XIAJIE() == null ? "" : bodyfat.getGGJR_XIAJIE().toString());
        testWholeData.setGgjrShangjie(bodyfat.getGGJR_SHANGJIE() == null ? "" : bodyfat.getGGJR_SHANGJIE().toString());
        testWholeData.setStzsfShicezhi(bodyfat.getSTZSF_SHICEZHI() == null ? "" : bodyfat.getSTZSF_SHICEZHI().toString());
        testWholeData.setStzsfXiajie(bodyfat.getSTZSF_XIAJIE() == null ? "" : bodyfat.getSTZSF_XIAJIE().toString());
        testWholeData.setStzsfShangjie(bodyfat.getSTZSF_SHANGJIE() == null ? "" : bodyfat.getSTZSF_SHANGJIE().toString());
        testWholeData.setDbzShicezhi(bodyfat.getDBZ_SHICEZHI() == null ? "" : bodyfat.getDBZ_SHICEZHI().toString());
        testWholeData.setDbzXiajie(bodyfat.getDBZ_XIAJIE() == null ? "" : bodyfat.getDBZ_XIAJIE().toString());
        testWholeData.setDbzShangjie(bodyfat.getDBZ_SHANGJIE() == null ? "" : bodyfat.getDBZ_SHANGJIE().toString());
        testWholeData.setWjyShicezhi(bodyfat.getWJY_SHICEZHI() == null ? "" : bodyfat.getWJY_SHICEZHI().toString());
        testWholeData.setWjyXiajie(bodyfat.getWJY_XIAJIE() == null ? "" : bodyfat.getWJY_XIAJIE().toString());
        testWholeData.setWjyShangjie(bodyfat.getWJY_SHANGJIE() == null ? "" : bodyfat.getWJY_SHANGJIE().toString());
        testWholeData.setXbwyShicezhi(bodyfat.getXBWY_SHICEZHI() == null ? "" : bodyfat.getXBWY_SHICEZHI().toString());
        testWholeData.setXbwyXiajie(bodyfat.getXBWY_XIAJIE() == null ? "" : bodyfat.getXBWY_XIAJIE().toString());
        testWholeData.setXbwyShangjie(bodyfat.getXBWY_SHANGJIE() == null ? "" : bodyfat.getXBWY_SHANGJIE().toString());
        testWholeData.setXbnyShicezhi(bodyfat.getXBNY_SHICEZHI() == null ? "" : bodyfat.getXBNY_SHICEZHI().toString());
        testWholeData.setXbnyXiajie(bodyfat.getXBNY_XIAJIE() == null ? "" : bodyfat.getXBNY_XIAJIE().toString());
        testWholeData.setXbnyShangjie(bodyfat.getXBNY_SHANGJIE() == null ? "" : bodyfat.getXBNY_SHANGJIE().toString());
        testWholeData.setZszjrlShicezhi(bodyfat.getZSZJRL_SHICEZHI() == null ? "" : bodyfat.getZSZJRL_SHICEZHI().toString());
        testWholeData.setZszjrlXiajie(bodyfat.getZSZJRL_XIAJIE() == null ? "" : bodyfat.getZSZJRL_XIAJIE().toString());
        testWholeData.setZszjrlShangjie(bodyfat.getZSZJRL_SHANGJIE() == null ? "" : bodyfat.getZSZJRL_SHANGJIE().toString());
        testWholeData.setYszjrlShicezhi(bodyfat.getYSZJRL_SHICEZHI() == null ? "" : bodyfat.getYSZJRL_SHICEZHI().toString());
        testWholeData.setYszjrlXiajie(bodyfat.getYSZJRL_XIAJIE() == null ? "" : bodyfat.getYSZJRL_XIAJIE().toString());
        testWholeData.setYszjrlShangjie(bodyfat.getYSZJRL_SHANGJIE() == null ? "" : bodyfat.getYSZJRL_SHANGJIE().toString());
        testWholeData.setQgjrlShicezhi(bodyfat.getQGJRL_SHICEZHI() == null ? "" : bodyfat.getQGJRL_SHICEZHI().toString());
        testWholeData.setQgjrlXiajie(bodyfat.getQGJRL_XIAJIE() == null ? "" : bodyfat.getQGJRL_XIAJIE().toString());
        testWholeData.setQgjrlShangjie(bodyfat.getQGJRL_SHANGJIE() == null ? "" : bodyfat.getQGJRL_SHANGJIE().toString());
        testWholeData.setZxzjrlShicezhi(bodyfat.getZXZJRL_SHICEZHI() == null ? "" : bodyfat.getZXZJRL_SHICEZHI().toString());
        testWholeData.setZxzjrlXiajie(bodyfat.getZXZJRL_XIAJIE() == null ? "" : bodyfat.getZXZJRL_XIAJIE().toString());
        testWholeData.setZxzjrlShangjie(bodyfat.getZXZJRL_SHANGJIE() == null ? "" : bodyfat.getZXZJRL_SHANGJIE().toString());
        testWholeData.setYxzjrlShicezhi(bodyfat.getYXZJRL_SHICEZHI() == null ? "" : bodyfat.getYXZJRL_SHICEZHI().toString());
        testWholeData.setYxzjrlXiajie(bodyfat.getYXZJRL_XIAJIE() == null ? "" : bodyfat.getYXZJRL_XIAJIE().toString());
        testWholeData.setYxzjrlShangjie(bodyfat.getYXZJRL_SHANGJIE() == null ? "" : bodyfat.getYXZJRL_SHANGJIE().toString());
        testWholeData.setZszzflShicezhi(bodyfat.getZSZZFL_SHICEZHI() == null ? "" : bodyfat.getZSZZFL_SHICEZHI().toString());
        testWholeData.setZszzflXiajie(bodyfat.getZSZZFL_XIAJIE() == null ? "" : bodyfat.getZSZZFL_XIAJIE().toString());
        testWholeData.setZszzflShangjie(bodyfat.getZSZZFL_SHANGJIE() == null ? "" : bodyfat.getZSZZFL_SHANGJIE().toString());
        testWholeData.setYszzflShicezhi(bodyfat.getYSZZFL_SHICEZHI() == null ? "" : bodyfat.getYSZZFL_SHICEZHI().toString());
        testWholeData.setYszzflXiajie(bodyfat.getYSZZFL_XIAJIE() == null ? "" : bodyfat.getYSZZFL_XIAJIE().toString());
        testWholeData.setYszzflShangjie(bodyfat.getYSZZFL_SHANGJIE() == null ? "" : bodyfat.getYSZZFL_SHANGJIE().toString());
        testWholeData.setQgzflShicezhi(bodyfat.getQGZFL_SHICEZHI() == null ? "" : bodyfat.getQGZFL_SHICEZHI().toString());
        testWholeData.setQgzflXiajie(bodyfat.getQGZFL_XIAJIE() == null ? "" : bodyfat.getQGZFL_XIAJIE().toString());
        testWholeData.setQgzflShangjie(bodyfat.getQGZFL_SHANGJIE() == null ? "" : bodyfat.getQGZFL_SHANGJIE().toString());
        testWholeData.setZxzzflShicezhi(bodyfat.getZXZZFL_SHICEZHI() == null ? "" : bodyfat.getZXZZFL_SHICEZHI().toString());
        testWholeData.setZxzzflXiajie(bodyfat.getZXZZFL_XIAJIE() == null ? "" : bodyfat.getZXZZFL_XIAJIE().toString());
        testWholeData.setZxzzflShangjie(bodyfat.getZXZZFL_SHANGJIE() == null ? "" : bodyfat.getZXZZFL_SHANGJIE().toString());
        testWholeData.setYxzzflShicezhi(bodyfat.getYXZZFL_SHICEZHI() == null ? "" : bodyfat.getYXZZFL_SHICEZHI().toString());
        testWholeData.setYxzzflXiajie(bodyfat.getYXZZFL_XIAJIE() == null ? "" : bodyfat.getYXZZFL_XIAJIE().toString());
        testWholeData.setYxzzflShangjie(bodyfat.getYXZZFL_SHANGJIE() == null ? "" : bodyfat.getYXZZFL_SHANGJIE().toString());
        testWholeData.setTzjgShijizhi(bodyfat.getTZJG_SHIJIZHI() == null ? "" : bodyfat.getTZJG_SHIJIZHI().toString());
        testWholeData.setTzjgXiajie(bodyfat.getTZJG_XIAJIE() == null ? "" : bodyfat.getTZJG_XIAJIE().toString());
        testWholeData.setTzjgShangjie(bodyfat.getTZJG_SHANGJIE() == null ? "" : bodyfat.getTZJG_SHANGJIE().toString());
        testWholeData.setBmiShicezhi(bodyfat.getBMI_SHICEZHI() == null ? "" : bodyfat.getBMI_SHICEZHI().toString());
        testWholeData.setBmiXiajie(bodyfat.getBMI_XIAJIE() == null ? "" : bodyfat.getBMI_XIAJIE().toString());
        testWholeData.setBmiShangjie(bodyfat.getBMI_SHANGJIE() == null ? "" : bodyfat.getBMI_SHANGJIE().toString());
        testWholeData.setZfljgFatW(bodyfat.getZFLJG_FAT_W() == null ? "" : bodyfat.getZFLJG_FAT_W().toString());
        testWholeData.setZfljgXiajie(bodyfat.getZFLJG_XIAJIE() == null ? "" : bodyfat.getZFLJG_XIAJIE().toString());
        testWholeData.setZfljgShangjie(bodyfat.getZFLJG_SHANGJIE() == null ? "" : bodyfat.getZFLJG_SHANGJIE().toString());
        testWholeData.setJrjgShijizhi(bodyfat.getJRJG_SHIJIZHI() == null ? "" : bodyfat.getJRJG_SHIJIZHI().toString());
        testWholeData.setStzsfjgShijizhi(bodyfat.getSTZSFJG_SHIJIZHI() == null ? "" : bodyfat.getSTZSFJG_SHIJIZHI().toString());
        testWholeData.setDbzjgShijizhi(bodyfat.getDBZJG_SHIJIZHI() == null ? "" : bodyfat.getDBZJG_SHIJIZHI().toString());
        testWholeData.setWjyjgShijizhi(bodyfat.getWJYJG_SHIJIZHI() == null ? "" : bodyfat.getWJYJG_SHIJIZHI().toString());
        testWholeData.setYtbShicezhi(bodyfat.getYTB_SHICEZHI() == null ? "" : bodyfat.getYTB_SHICEZHI().toString());
        testWholeData.setYtbXiajie(bodyfat.getYTB_XIAJIE() == null ? "" : bodyfat.getYTB_XIAJIE().toString());
        testWholeData.setYtbShangjie(bodyfat.getYTB_SHANGJIE() == null ? "" : bodyfat.getYTB_SHANGJIE().toString());
        testWholeData.setFzxsShicezhi(bodyfat.getFZXS_SHICEZHI() == null ? "" : bodyfat.getFZXS_SHICEZHI().toString());
        testWholeData.setFzxsXiajie(bodyfat.getFZXS_XIAJIE() == null ? "" : bodyfat.getFZXS_XIAJIE().toString());
        testWholeData.setFzxsShangjie(bodyfat.getFZXS_SHANGJIE() == null ? "" : bodyfat.getFZXS_SHANGJIE().toString());
        testWholeData.setJhfxShangzhi(bodyfat.getJHFX_SHANGZHI() == null ? "" : bodyfat.getJHFX_SHANGZHI().toString());
        testWholeData.setJhfxXiazhi(bodyfat.getJHFX_XIAZHI() == null ? "" : bodyfat.getJHFX_XIAZHI().toString());
        testWholeData.setStllfxShangzhi(bodyfat.getSTLLFX_SHANGZHI() == null ? "" : bodyfat.getSTLLFX_SHANGZHI().toString());
        testWholeData.setStllfxXiazhi(bodyfat.getSTLLFX_XIAZHI() == null ? "" : bodyfat.getSTLLFX_XIAZHI().toString());
        testWholeData.setStllfxJirou(bodyfat.getSTLLFX_JIROU() == null ? "" : bodyfat.getSTLLFX_JIROU().toString());
        testWholeData.setShentinianling(bodyfat.getSHENTINIANLING() == null ? "" : bodyfat.getSHENTINIANLING().toString());
        testWholeData.setTizhongtiaojie(bodyfat.getTIZHONGTIAOJIE() == null ? "" : bodyfat.getTIZHONGTIAOJIE().toString());
        testWholeData.setZhifangtiaojie(bodyfat.getZHIFANGTIAOJIE() == null ? "" : bodyfat.getZHIFANGTIAOJIE().toString());
        testWholeData.setJiroutiaojie(bodyfat.getJIROUTIAOJIE() == null ? "" : bodyfat.getJIROUTIAOJIE().toString());
        testWholeData.setDxJichudaixie(bodyfat.getDX_JICHUDAIXIE() == null ? "" : bodyfat.getDX_JICHUDAIXIE().toString());
        testWholeData.setDxZongnengliangxiaohao(bodyfat.getDX_ZONGNENGLIANGXIAOHAO() == null ? "" : bodyfat.getDX_ZONGNENGLIANGXIAOHAO().toString());
        testWholeData.setFbzfShicezhi(bodyfat.getFBZF_SHICEZHI() == null ? "" : bodyfat.getFBZF_SHICEZHI().toString());
        testWholeData.setPostureone(bodyfat.getPosture_one());
        testWholeData.setPosturetwo(bodyfat.getPosture_two());
        testWholeData.setScore(bodyfat.getScore() == null ? "" : bodyfat.getScore().toString());
        testWholeData.setTzlspecifictime(StringUtils.trimToEmpty(bodyfat.getSpecificTime()));
        testWholeData.setTzltablegps(StringUtils.trimToEmpty(bodyfat.getGps()));
    }



    // 通用DTO数据处理方法
    private void applyItemData(TestCorporeityDTO dto,
                               Consumer<Float> valueSetter,
                               Consumer<Float> scoreSetter,
                               Consumer<String> gradeSetter,
                               Consumer<String> timeSetter) {
        if (dto != null) {
            if (valueSetter != null) valueSetter.accept(toSafeFloat(dto.getTestValue()));
            if (scoreSetter != null) scoreSetter.accept(toSafeFloat(dto.getScore()));
            if (gradeSetter != null) gradeSetter.accept(StringUtils.trimToEmpty(dto.getGrade()));
            if (timeSetter != null) timeSetter.accept(StringUtils.trimToEmpty(dto.getSpecificTime()));
        }
    }
    // 特殊项目处理示例（项目2只有值和时间）
    private void applyItemData(TestCorporeityDTO dto,
                               Consumer<Float> valueSetter,
                               Consumer<String> timeSetter) {
        if (dto != null) {
            if (valueSetter != null) valueSetter.accept(toSafeFloat(dto.getTestValue()));
            if (timeSetter != null) timeSetter.accept(StringUtils.trimToEmpty(dto.getSpecificTime()));
        }
    }
}